How to bind an ObservableCollection to a Listbox of Checkboxes in WPF

前端 未结 3 598
你的背包
你的背包 2021-01-06 16:38

Let me prefix this question by stating that I\'m very new to both C# and WPF.

I\'m trying to connect a collection of Boolean values to a container conta

3条回答
  •  忘掉有多难
    2021-01-06 16:53

    Use IsChecked="{Binding}" to bind the item of the collection directly.

    
        
            
                
            
        
    
    

    However it is not possible to do bind to source with this method. Because the binding on the IsChecked property of the CheckBox doesn't the index of the item of the binding. So, it can't change the collection but only the item of the collection.

    Update

    To get around that limitation, you can create a wrapper to the Boolean value:

    public class Wrapper : INotifyPropertyChanged
    {
        private T value;
        public T Value
        {
            get { return value; }
            set
            {
                {
                    this.value = value;
                    OnPropertyChanged();
                }
            }
        }
    
        public static implicit operator Wrapper(T value)
        {
            return new Wrapper { value = value };
        }
        public static implicit operator T(Wrapper wrapper)
        {
            return wrapper.value;
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    Here is an exemple of usage:

    public partial class MainWindow : Window
    {
        public ObservableCollection> MyBooleanCollection { get; private set; }
    
        public MainWindow()
        {
            InitializeComponent();
    
            DataContext = this;
            MyBooleanCollection = new ObservableCollection>() { false, true, true, false, true };
        }
    }
    

    And in the XAML:

    
    

提交回复
热议问题