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?
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
}
};
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With