Search code examples
wpfcollectionviewinotifycollectionchanged

How to destroy or detach a CollectionView


I observe an odd behaviour of WPF ItemsControls: If a set the ItemsSource to an object which implements INotifyCollectionChanged and after that set the ItemsSource to null, the CollectionView which was created to provide the data to the ItemsControl still listens to the CollectionChanged-event of the source object.
If now the source collection is changed through a different thread, the CollectionView throws an exception (without being attached to any control). While I understand why this is happening, I’m really stuck resolving this situation.

Therefore the main question is, how can I destroy a CollectionView so that it does not listen any more to CollectionChanged-event. Or how can I disable it doing that / detaching the underlying collection.

Please note: The described behavior is not with ObservableCollection. The source object is an IEnumerable of T and implements INotifyCollectionChanged.


Solution

  • You're looking for the CollectionView.DetachFromSourceCollection() method:

    var collectionView = CollectionViewSource.GetDefaultView(yourEnumerable) as CollectionView;
    collectionView.DetachFromSourceCollection();