7

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

I believe there isn't an actual event, but perhaps a way to filter the CollectionChanged event?

Wilson
  • 8,570
  • 20
  • 66
  • 101

2 Answers2

15

The CollectionChanged event includes information such as what action was performed on the collection (e.g., add or remove) and what items were affected.

Just add a check in your handler to only perform the desired action if an Add was performed.

ObservableCollection<T> myObservable = ...;
myObservable.CollectionChanged += (sender, e) =>
{
    if (e.Action == NotifyCollectionChangedAction.Add)
    {
        // do stuff
    }
};
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
1

Subclassing the ObservableCollection class and create your own ItemAdded event should work I would 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);
    }
}
Olav Nybø
  • 11,454
  • 8
  • 42
  • 34
  • 2
    If subclassing, it would be better to override the `OnCollectionChanged()` method to add this logic. This would prevent client code from removing the handler. – Jeff Mercado Feb 24 '13 at 20:50