开发者

Removing event handlers in wpf window

开发者 https://www.devze.com 2022-12-19 10:27 出处:网络
In our wpf app we are adding events in the constructor of our window like this: AddHandler(Keyboard.KeyUpEvent, (KeyEventHandler)HandleKeyDownEvent);

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

精彩评论

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