Remove an item from an ObservableCollection in a CollectionChanged event handler

后端 未结 5 663
逝去的感伤
逝去的感伤 2021-02-02 01:13

I\'m hoping to be able to reject some items after they have been added to an ObservableCollection. I am not able to subclass the ObservableCollection or use any sort of view, s

5条回答
  •  眼角桃花
    2021-02-02 01:52

    if you really want to modify a collection you are going to want to iterate through a copy of the collection. its because you are trying to modify the collection in the foreach loop thats causing you grief.

    example

    var copy = new ObservableCollection(collection)
    foreach(var item in copy)
    {
        if(item.Name == "Fred")
        {
            collection.Remove(item);
        }
    
    }
    

    that said, I agree with Anurag that you shouldn't be doing this type of thing with an observablecollection and certainly not inside a CollectionChanged Event.

提交回复
热议问题