Remove one Item in ObservableCollection

后端 未结 3 716
情话喂你
情话喂你 2021-01-04 05:34

I have some method like:

public void RemoveItem(ObservableCollection collection, SomeClass instance)
{
    if(collection.Contains(instance))         


        
3条回答
  •  被撕碎了的回忆
    2021-01-04 06:14

    Your problem is that you are trying to remove an object from the collection that is not in that collection. It might have the same property values, but it is not the same object. There is a simple way around this if your object has a uniquely identifiable property, such as Id:

    public void RemoveItem(ObservableCollection collection, SomeClass instance)
    {
        collection.Remove(collection.Where(i => i.Id == instance.Id).Single());
    }
    

    The idea is that we are getting the actual item from the collection and then passing that into the Remove method.

提交回复
热议问题