好的,所以我有一个附加属性(在静态类中声明),它将属性附加INotifyCollectionChanged
到对象。
设置属性后,我想开始监视集合的更改,然后对集合附加到的对象执行一些操作。
第一次尝试:
private static void MyProperty_OnChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
// We need both the dependency object, and the collection args to process the notification
NotifyCollectionChangedEventHandler changedFunc = (sender, eventArgs) => MyProperty_OnCollectionChanged( d, sender, eventArgs );
if( e.OldValue != null )
e.OldValue.CollectionChanged -= changedFunc; // Can you see the bug?
if( e.NewValue != null )
e.NewValue.CollectionChanged += changedFunc;
}
为了将集合附加到处理程序中的对象,我拉d
入闭包。很容易,对吧?
好吧,我相信你可以在这里看到这个错误。当集合被删除或替换为新集合时,它无法取消注册事件处理程序,因为 changedFunc 是具有不同闭包的新处理程序。
那么,这样做的正确方法是什么?