remove lambda expression from PropertyChanged (equivalent of p.PropertyChanged -= (s,a) => { ... })

514 Views Asked by At

I have a class that implements PropertyChanged. I do something similar to this to subscribe to it:

p.PropertyChanged += (s, a) => {
    switch ( a.PropertyName) {
        ...
    }
}

How can I later unsubscribe the above code from the p.PropertyChanged ? Equivalent of (which clearly won't work):

p.PropertyChanged -= (s, a) => {
    switch ( a.PropertyName) {
        ...
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

You must put it in a variable:

PropertyChangedEventHandler eventHandler = (s, a) => {
    ...
};

// ...
// subscribe
p.PropertyChanged += eventHandler;
// unsubscribe
p.PropertyChanged -= eventHandler;

From the docs:

It is important to notice that you cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, it is necessary to go back to the code where you subscribe to the event, store the anonymous method in a delegate variable, and then add the delegate to the event. In general, we recommend that you do not use anonymous functions to subscribe to events if you will have to unsubscribe from the event at some later point in your code.

1
On

As an addition to @Sweeper's answer, you can accomplish the same using event handler method, without the burden of lambda expressions:

private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    switch (e.PropertyName) 
    {
        ...
    }
}

Which you can then use to subscribe to the PropertyChanged event:

p.PropertyChanged += OnPropertyChanged;

And to unsubscribe:

p.PropertyChanged -= OnPropertyChanged;

Additional info from the docs:

To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you are handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button. To receive notifications when the event occurs, your event handler method must subscribe to the event.