ObservableCollection event for items being added, but not removed

10,941

Solution 1

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
    }
};

Solution 2

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);
    }
}
Share:
10,941
Wilson
Author by

Wilson

Updated on June 11, 2022

Comments

  • Wilson
    Wilson about 2 years

    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?

  • Jeff Mercado
    Jeff Mercado over 11 years
    If subclassing, it would be better to override the OnCollectionChanged() method to add this logic. This would prevent client code from removing the handler.