简体   繁体   English

从 PropertyChanged 中删除 lambda 表达式(相当于 p.PropertyChanged -= (s,a) => {... })

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

I have a class that implements PropertyChanged.我有一个实现 PropertyChanged 的 class。 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 ?我以后如何从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.请务必注意,如果您使用匿名 function 订阅活动,则无法轻易取消订阅该活动。 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.在这种情况下取消订阅,需要go回到你订阅事件的代码,将匿名方法存储在委托变量中,然后将委托添加到事件中。 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.一般而言,如果您必须在稍后的代码中取消订阅事件,我们建议您不要使用匿名函数来订阅事件。

As an addition to @Sweeper's answer, you can accomplish the same using event handler method, without the burden of lambda expressions:作为@Sweeper 答案的补充,您可以使用事件处理程序方法完成相同的操作,而无需 lambda 表达式的负担:

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

Which you can then use to subscribe to the PropertyChanged event:然后您可以使用它来订阅PropertyChanged事件:

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.要在事件发生时接收通知,您的事件处理程序方法必须订阅该事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM