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) {
...
}
}
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.