简体   繁体   中英

Handling Keyboard events WPF

In my WPF MVVM application, I am subscribing to PreviewKeyUp and PreviewKeyDown in UserControl1.xaml.cs as such:

UserControl1_Loaded(object sender, RoutedEventArgs e)
{
    var window = Window.GetWindow(this);
    window.PreviewKeyUp += UserControl1_PreviewKeyUp;
    window.PreviewKeyDown += UserControl1_PreviewKeyDown;
}

Should I worry about a memory leak? Do I have to unsubscribe from these events in the Unloaded event or will the GC take care of it?

Should I worry about a memory leak?

Only if the parent window that publish the events lives longer than the UserControl that subscribes to the event.

Do I have to unsubscribe from these events in the Unloaded event or will the GC take care of it?

You need to unexplicitly unsubscribe for the window not to keep the UserControl instance alive. Again, this is not an issue if the both the window and the UserControl become eligible for garbage collection at the same time.

The garbage collector never unsubscribe from any events for you though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM