Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableCollection event for items being added, but not removed

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?

like image 973
Wilson Avatar asked Feb 24 '13 19:02

Wilson


2 Answers

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
    }
};
like image 57
Jeff Mercado Avatar answered Sep 20 '22 10:09

Jeff Mercado


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);
    }
}
like image 24
Olav Nybø Avatar answered Sep 21 '22 10:09

Olav Nybø