How to implement the INotifyCollectionChanged interface?

奇 卢 181 Reputation points
2021-05-15T03:30:41.487+00:00

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 Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,784 questions
0 comments No comments
{count} votes

Accepted answer
  1. DaisyTian-1203 11,626 Reputation points
    2021-05-17T02:03:39.793+00:00

    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.