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 は別のクロージャーを持つ新しいハンドラーであるため、イベント ハンドラーの登録解除に失敗します。
それで、これを行う正しい方法は何ですか?