Martin
Martin

Reputation: 2096

How to make ListBox remove a CollectionChanged event handler from its ItemsSource

Having a ListBox, a

listBox.ItemsSource = myObservableCollection;

will add an event handler to myObservableCollection.CollectionChanged.

But

listBox.ItemsSource = null;

or

listBox.ItemsSource = anotherObservableCollection;

won’t remove the event handler from myObservableCollection.CollectionChanged.

How can I make the ListBox remove its event handler from that event?

That the event handler actually isn’t removed can be seen e.g. when using something like this:

class MyObservableCollection<T> : ObservableCollection<T>
{
    public override event NotifyCollectionChangedEventHandler? CollectionChanged
    {
        add { Trace.WriteLine("add"); base.CollectionChanged += value; }
        remove { Trace.WriteLine("remove"); base.CollectionChanged -= value; }
    }
}

Upvotes: 0

Views: 70

Answers (1)

mm8
mm8

Reputation: 169350

How can I make the ListBox remove its event handler from that event?

Use the DetachFromSourceCollection method of the CollectionView:

CollectionView view = CollectionViewSource.GetDefaultView(listBox.ItemsSource)
    as CollectionView;
view?.DetachFromSourceCollection();
listBox.ItemsSource = null;

Upvotes: 1

Related Questions