Remove one Item in ObservableCollection

后端 未结 3 737
情话喂你
情话喂你 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: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)

提交回复
热议问题