Implementing the INotifyCollectionChanged Interface

I need to implement a collection with accessibility features. Also, I want to bind this collection to a ListView, so I ended up with the following code (I skipped some methods to make it shorter here in the forum):

public class myCollection<T> : INotifyCollectionChanged { private Collection<T> collection = new Collection<T>(); public event NotifyCollectionChangedEventHandler CollectionChanged; public void Add(T item) { collection.Insert(collection.Count, item); OnCollectionChange(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item)); } protected virtual void OnCollectionChange(NotifyCollectionChangedEventArgs e) { if (CollectionChanged != null) CollectionChanged(this, e); } } 

I wanted to test it with a simple data class:

 public class Person { public string GivenName { get; set; } public string SurName { get; set; } } 

So, I created an instance of the myCollection class as follows:

 myCollection<Person> _PersonCollection = new myCollection<Person>(); public myCollection<Person> PersonCollection { get { return _PersonCollection; } } 

The problem is that the ListView does not update when the collection is updated, although I implemented the INotifyCollectionChanged interface.

I know that my binding is fine (in XAML) because when I use the ObservableCollecion class instead of the myCollecion class as follows:

  ObservableCollection<Person> _PersonCollection = new ObservableCollection<Person>(); public ObservableCollection<Person> PersonCollection { get { return _PersonCollection; } } 

ListView updates

What is the problem?

+4
source share
1 answer

In order for your collection to be consumed, you must implement IEnumerable and IEnumerator. Although you are probably better off subclassing the ObservableCollection<T>

+2
source

Source: https://habr.com/ru/post/1333302/


All Articles