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

Time:03-23

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; }
    }
}

CodePudding user response:

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;
  • Related