I have some method like:
public void RemoveItem(ObservableCollection<SomeClass> collection, SomeClass instance)
{
if(collection.Contains(instance))
{
collection.Remove(instance);
}
}
First, even the collection contains the instance, the if
sentence still return false
.
Second, I delete the if sentence, just make the collection can remove the instance. And after the execution the collection still kept its original items, which still include instance.
Is it the Reference problem, but how to fix it? I just want to remove one item from the ObservableCollection and keep its Observable functionality (which puzzled me here).
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.
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;
}
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With