Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing collection from CollectionChanged event

I want to update collection after it was changed but I can't seem to get "away" from this exception:

Cannot change ObservableCollection during a CollectionChanged or PropertyChanged event.

Inside event handler I unsubscribe from Collection changed event before changing anything to prevent infinite loops and after changes are made i subscribe again to same event.

private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    data.CollectionChanged -= CollectionChanged;
    data.Add("Item");
    data.CollectionChanged += CollectionChanged;
}

I tried using Dispatcher to call data.Add("Item"), but no luck :(

like image 775
Kestutis Avatar asked Apr 10 '26 07:04

Kestutis


1 Answers

The problem is that you are unsubscribing from the event within the event which has yet to complete. Drop back and re-evaluate why you are adding to the collection and determine if there is another way to accomplish what you need.

like image 51
DaveWilliamson Avatar answered Apr 11 '26 22:04

DaveWilliamson