在WPF窗口中移除事件处理程序

5
在我们的WPF应用程序中,我们使用以下方式在窗口的构造函数中添加事件:
AddHandler(Keyboard.KeyUpEvent, (KeyEventHandler)HandleKeyDownEvent);

        this.Closing += new System.ComponentModel.CancelEventHandler(WindowF_Closing);
        this.Loaded += new RoutedEventHandler(WindowF_Loaded);

在关闭事件中移除这些事件以便窗口被处理,这个想法是否可行:

RemoveHandler(Keyboard.KeyUpEvent, (KeyEventHandler)HandleKeyDownEvent);

        this.Closing -= new System.ComponentModel.CancelEventHandler(WindowF_Closing);
        this.Loaded -= new RoutedEventHandler(WindowF_Loaded);
1个回答

8

只有当事件的发布者比订阅者存在时间更长时,才需要显式地删除事件处理程序。

在您的情况下,ClosingLoaded事件的发布者是窗口本身,因此无需取消订阅该事件。然而,键盘将存在很长时间,因此从KeyUpEvent中取消订阅是一个好主意。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接