question

58901228 avatar image
0 Votes"
58901228 asked DaisyTian-1203 answered

How to implement the INotifyCollectionChanged interface?


I assign a List<int> to the ItemsSource of ListBox, and the form inherits the INotifyCollectionChanged interface. However, when I delete the value in the List<int>, the CollectionChanged event will be null. How can I implement this interface?

my code example:

 ... 
 private List<int> myin = new List<int>();
    
         public event NotifyCollectionChangedEventHandler CollectionChanged;
    
         //Remove a number.
         private void Button_Click(object sender, RoutedEventArgs e)
         {
             myin.Remove(34);
             if (CollectionChanged != null) CollectionChanged(this,
                 new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,myin));
         }
    
         //initalize List<int> and binding to ListBox.ItemsSource.
         private void Window_Loaded(object sender, RoutedEventArgs e)
         {
             for(int i = 0; i < 100; i++)
             {
                 myin.Add(i);
             }
             lis.ItemsSource = myin;
         }
windows-wpf
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

DaisyTian-1203 avatar image
0 Votes"
DaisyTian-1203 answered

Please use ObservableCollection to replace List, WPF provides the ObservableCollection<T> class, which is a built-in implementation of a data collection that implements the INotifyCollectionChanged interface.
Please update your myin and Button_Click as :

  ObservableCollection<int> myin = new ObservableCollection<int>();
         private void Button_Click(object sender, RoutedEventArgs e)
         {
             myin.Remove(34);
         }

Then your demo will work like below:
96938-3.gif


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


3.gif (14.9 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.