Bind a control to a single value in a collection/array in WPF

前端 未结 3 1900
轮回少年
轮回少年 2021-01-06 09:53

In WPF I have a collection of bool? values and I want to bind each of these to a separate checkbox programmatically. I want the bindings to be TwoWay so that changing the va

3条回答
  •  醉梦人生
    2021-01-06 10:18

    There are a few things that need changing here to get this to work. Firstly you'll need to wrap your boolean value in an object that implements the INotifyPropertyChanged interface in order to get the change notification that you are looking for. Currently you are binding to boolean values in your collection which do not implement the interface. To do this you could create a wrapper class like so :

      public class Wrapper: INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
    
            private bool val = false;
    
            public bool Val
            {
                get { return val; }
                set
                {
                    val = value;
                    this.OnPropertyChanged("Val");
                }
            }
    
            public Wrapper(bool val)
            {
                this.val = val;
            }
    
        }
    

    You'll then want to create these objects in your form instead of a list of booleans. You may also want to use an observable collection instead of a list so that notification of items being added and removed are sent. This is shown below:

    public Window1()
        {
            InitializeComponent();
            this.DataContext = this;
        }
    
        private ObservableCollection myCollection = new ObservableCollection()
            {new Wrapper(true), new Wrapper(false), new Wrapper(true)};
    
    
        public ObservableCollection MyCollection
        {
            get { return myCollection; }
        }
    

    The next thing to do is to display a list of check boxes in your ui. To do this WPF provides itemscontrols. ListBox is an itemscontrol so we can use this as a starting point. Set the itemssource of a listbox to be MyCollection. We then need to define how each Wrapper object is going to be displayed in the list box and this can be done with a datatemplate which is created in the windows resources. This is shown below :

    
        
            
        
    
    
        
    
    

    This should get you up and running with a simple demo of checkboxes that have values bound to a list of booleans.

提交回复
热议问题