在我们的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
事件的发布者是窗口本身,因此无需取消订阅该事件。但是,键盘将存在很长一段时间,因此退订KeyUpEvent
是个好主意。