Reputation: 2273
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?
Upvotes: 4
Views: 5597
Reputation: 8944
You seem to be under the impression that you can remove multiple items from an ObservableCollection
with a single method call. This is not possible. You have to call either Remove
, RemoveAt
, or RemoveItem
and all of these only remove a single element from the collection. This means that each time an item is removed from the collection, the remove event will fire and the OldStartingIndex
and OldItems
will contain a reference to the index of the one item that was removed and a single element array of the one item respectively.
You cannot do a lookup in the collection using the OldStartingIndex
as you have noted because it has been removed. If you need access to the item that was original referenced there you can use OldItems
and take the first element.
I have not used ObservableCollection
but the only way I see to remove more than one element at a single time is to call Clear
or ClearItems
. If these fire a changed event then I would imagine that OldStartingIndex
would be 0 and OldItems
would contain a reference to all the elements that were previously in the collection.
Upvotes: 1
Reputation: 141638
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.
Upvotes: 7
Reputation: 112352
The event argument e
has the properties OldItems
and OldStartingIndex
. May be this helps?
Upvotes: 1
Reputation: 27343
Yes. OldStartingIndex
in the NotifyCollectionChangedEventArgs
is the index from which the item was removed.
Upvotes: 1