开发者

Removing event handlers in wpf window

In our wpf app we are adding events in the constructor of our window like this:

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

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

Is it a good idea to remove these events in the closing event so that the window is disposed:

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

        this.Closing -= new System.ComponentModel.CancelEventHandler(WindowF_C开发者_运维百科losing);
        this.Loaded -= new RoutedEventHandler(WindowF_Loaded);


You only need to remove event handlers explicitly if the publisher of the event lives for longer than the subscriber.

In your case, the publisher of the Closing and Loaded events is the window itself, so there's no need to unsubscribe from the event. The Keyboard, however will be around for a long time, so unsubscribing from the KeyUpEvent is a good idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜