ObservableCollection event for added but not deleted items

Is there a way to fire an event when an item is added to an ObservableCollection, but not when removed?

I believe there is no real event, but maybe a way to filter the CollectionChanged event?

+4
source share
2 answers

The CollectionChanged event includes information, for example, what action was performed in the collection (for example, adding or removing) and which elements were affected.

Just add the check to the handler to only perform the required action if Add was executed.

 ObservableCollection<T> myObservable = ...; myObservable.CollectionChanged += (sender, e) => { if (e.Action == NotifyCollectionChangedAction.Add) { // do stuff } }; 
+11
source

Subclassing the ObservableCollection class and creating your own ItemAdded event should work, I think.

 public class MyObservableCollection<T> : ObservableCollection<T> { public event EventHandler<NotifyCollectionChangedEventArgs> ItemAdded; public MyObservableCollection() { CollectionChanged += MyObservableCollection_CollectionChanged; } void MyObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) ItemAdded(sender, e); } } 
+1
source

All Articles