C # ObservableCollection OnCollectionChanged not working when element changes

From MSDN on OnCollectionChanged: "Occurs when an item is added, deleted, modified, moved, or the entire list is updated."

I am changing a property attached to an object that is in my collection, but OnCollectionChanged does not start. I am implementing iNotifyPropertyChanged in the obj class.

public class ObservableBatchCollection : ObservableCollection<BatchData> { protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if(e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add) { foreach (BatchData item in e.NewItems) { } } base.OnCollectionChanged(e); } public ObservableBatchCollection(IEnumerable<BatchData> items) : base(items) { } } 

For me, this means that when an element in the collection changes, for example, a property of an object, this event should fire. This is not true. I want to know when an item in my user collection changes so that I can perform a calculation on it if necessary.

Any thoughts?

+4
source share
1 answer

ObservableCollection<T> raises events only when the collection itself changes. An element contained in a collection with an internal changed state has not changed the structure of the collection, and the ObservableCollection<T> will not report this.

One option is to subclass ObservableCollection<T> and subscribe to each OnPropertyChanged element when it is added. In this handler, you can raise either a custom event, or return to the collection’s own PropertyChanged event. Please note: if you are following this route, you must add a general restriction to T : INotifyPropertyChanged .

+7
source

All Articles