Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableCollection<T> CollectionChanged event

Tags:

c#

wpf

c#-4.0

I have an observable collection and I have a collectionChanged event wired up on that. I have its items bound to a listbox in the UI. When the user removes some items in the UI from the listbox, the CollectioChanged gets fired properly, however, I need to know the indices of the items that were removed. The problem is I am not able to an indexOf on the collection after it is changed because it does not have the removed item anymore..

Can we get access to the list of indexes that were removed from an ObservableCollection from the collectionchanged event?

like image 292
user1202434 Avatar asked Dec 28 '22 01:12

user1202434


1 Answers

The CollectionChanged event uses an event that gives you a NotifyCollectionChangedEventArgs. This has a OldStartingIndex property, which will tell you the index it was removed at. For example:

void Foo()
{
    ObservableCollection<string> r = new ObservableCollection<string>();
    r.CollectionChanged += r_CollectionChanged;
}

static void r_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    var itemRemovedAtIndex = e.OldStartingIndex;
}

Assume that I am removing MULTIPLE items from the collection at different indices..So using the oldStartingIndex would just give me the first item index that was removed

The event will most likely fire multiple times, once for each item.

like image 168
vcsjones Avatar answered Jan 08 '23 21:01

vcsjones