如何使 ListBox 从其 ItemsSource 中删除 CollectionChanged 事件处理程序

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

有一个ListBox,一个

listBox.ItemsSource = myObservableCollection;

将向 myObservableCollection.CollectionChanged 添加一个事件处理程序。

但是

listBox.ItemsSource = null;

listBox.ItemsSource = anotherObservableCollection;

不会从 myObservableCollection.CollectionChanged 中删除事件处理程序。

如何使 ListBox 从该事件中删除其事件处理程序?

可以看到事件处理程序实际上没有被删除,例如使用这样的东西时:

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

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

使用CollectionViewDetachFromSourceCollection方法:

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