I want to know how to unsubscribe anonymous methods from the events.
I have already checked Unsubscribe anonymous method in C# but my case is little different.
I am accessing local function variable in the anonymous method.
Code is as below
private static void Test(Object dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
if (dependencyPropertyChangedEventArgs.OldValue is ObservableCollection<object>)
{
(dependencyPropertyChangedEventArgs.OldValue as ObservableCollection<object>).CollectionChanged -=
(s, e) => SelectedItemsChanged(dependencyObject, e); // TO FIX event unbsubscription via anonymous delegate
}
if (dependencyPropertyChangedEventArgs.NewValue is ObservableCollection<object>)
{
(dependencyPropertyChangedEventArgs.NewValue as ObservableCollection<object>).CollectionChanged +=
(s, e) => SelectedItemsChanged(dependencyObject, e);
}
}
New answer, now the question has changed
You can’t, basically. Your handler depends on
dependencyObject, which will be captured in a new object on each call, so you’ll end up with unequal delegates.You could create a new class which holds the dependency object and overrides
Equalsto compare those objects instead of using anonymous functions, or you could just hold a reference to the previously-subscribed handler.Old answer, when the delegate didn’t depend on the parameters
The bizarre thing is that in this particular case, it looks like you’re not capturing any local variables. So it’s possible that if the only place you’re subscribing to the event is from this method, you could get away with:
As you’ve only got one lambda expression now, I’d expect that to be converted into a single static method, so the freshly-created delegate will be equal to the original one.
However, I wouldn’t recommend that. I’d just create the method yourself, and then use a method group conversion.