在我们的 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);
最佳答案
如果事件的发布者比订阅者存活的时间长,您只需要显式删除事件处理程序。
在您的情况下,Closing
的发布者和 Loaded
events 是窗口本身,因此无需取消订阅该事件。然而,键盘会存在很长时间,所以取消订阅 KeyUpEvent
是个好主意。
关于wpf - 在 wpf 窗口中删除事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2229488/