Search code examples
wpflistviewobservablecollectionselectionchanged

ListView selection change doesn't remove an old item


I have a strange behavior with my WPF ListView Control.
ListViews ItemSource is Observable collection.the ItemSource is updated periodically.
When I'm selecting one of the item and then selecting other item and no item updated, everything is OK.
But when I'm selecting an item witch is updated while I'm standing on, then selecting other item, now I have two items selected instead of one.
When I'm looking with the debugger, I see the event args of SelectionChanged event. I see that added item is OK but no removed item.
Anyone knows what's the problem?
Thanks!

Edit:

My observable collection:

    protected class CustomObservableCollection : ObservableCollection<T>
    {
        public void Refresh()
        {
            ListCollectionView lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(this));
            lcv.Refresh();
        }
    }

The update method witch called when there is a change in some item:

    public void RefreshItem(T domainObject)
    {
        foreach (T item in obsCollection) {
            if (!DomainObjectComparer.Equals(domainObject, item)) continue;
            DomainObjectCopier.CopyProperties(domainObject, item);
            obsCollection.Refresh();
            break;
        }
    }

Solution

  • Well, Apparently the problem was with the overridden GetHashCode() method of the ListView item object. the hash code included all the fields in it's calculation. I remoed all the fields (properties) and now the overridden GetHashCode() is only calculating the hash based on item's ID. it solved the problem.
    I also have Equals() method overridden.
    If someone knows why it is related I will like to know.