Remove one Item in ObservableCollection

后端 未结 3 717
情话喂你
情话喂你 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 05:57

    If the item you intend to remove has something like a code/id you could compare to other item, you could do something in the lines of:

    foreach (var item in itemSet)
    {
      if (item.ItemID == itemToCompareTo.ItemID)
      {
        itemSet.Remove(item);
        break;
      }
    }
    
    0 讨论(0)
  • 2021-01-04 06:03

    It seems to be a reference problem, indeed. You may have to override Equals (and GetHashCode) methods in order to the ObservableCollection to be able to find the instance, even if it is not the same reference.

    The reason is because the default implementation of the Equals() method checks to see if the two objects have the same reference.

    Note : be careful when overriding Equals method. You will have to also override GetHashCode, because the default implementation of the GetHashCode() method returns an integer based on the object's reference and is not based on the values of instance (and class) variables of the object.

    No matter how many times the values of its instance variables (data fields) change, the hash code calculated by the default implementation does not change during the life of the object. That's why we always implement GetHashCode() when you are overriding the Equals() method.

    More about this on msdn : Object.Equals Method (Object)

    0 讨论(0)
  • 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<SomeClass> 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.

    0 讨论(0)
提交回复
热议问题