np.
np.

Reputation: 2379

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_Closing);
        this.Loaded -= new RoutedEventHandler(WindowF_Loaded);

Upvotes: 5

Views: 5647

Answers (1)

Samuel Jack
Samuel Jack

Reputation: 33270

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.

Upvotes: 8

Related Questions