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

前端 未结 3 593
你的背包
你的背包 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:49

    By the link that you provided, you could also use INotifyPropertyChanged extension to your CheckedListItem class, but thats if you dont want use ObservableCollection. It would be something like this:

    public class CheckedListItem : INotifyPropertyChanged
    {
        private int _Id;
        public int Id 
        {
            get;
            set; NotifyIfAnythingChanged("Id");
        }
    
        private string _Name;
        public string Name
        {
            get;
            set; NotifyIfAnythingChanged("Name");
        }
    
        private bool _IsChecked;
        public bool IsChecked
        {
            get;
            set; NotifyIfAnythingChanged("IsChecked");
        }
    
        private void NotifyIfAnythingChanged(String propName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
    

    Your listbox should be something like this:

    
        
            
                
            
        
    
    

    In your code behind you should initialize the ObservableCollection just once, because every change made into it will result into an UI update.

    ObservableCollection MyList = new ObservableCollection();
    MyListBox.ItemsSource = MyList;
    

    Now every change made into MyList, such as Add(), Remove(), Etc. Will affect your UI.

提交回复
热议问题