Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Window.Close() not triggering UserControl.Unloaded event

I have a Window that contains a custom UserControl. The UserControl needs to know when the Window containing it has been closed so that it can terminate a thread.

My best guess as to how to accomplish this is to handle the UserControl's Unloaded event. However, the Unloaded event only seems to be firing when the user actually clicks to close the window, but not when I programmatically call the Close() method on the window.

For reference sake, here are some of the relevant parts of my code.

MyWindow.xaml:

<Window x:Class="Namespace.MyWindow"         xmlns:controls="clr-namespace:Namespace.Controls">     <controls:MyControl/> </Window> 

MyControl.xaml:

<UserControl x:Class="Namespace.Controls.MyControl"              Unloaded="UserControl_Unloaded"/>     <!-- Stuff --> </UserControl> 

MyControl.xaml.cs:

void UserControl_Unloaded(object sender, RoutedEventArgs e) {     // Stop the thread. } 

So just to recap, the UserControl_Unloaded() method above is getting called when I close the window "manually" (alt-F4, click the red "X", etc.), but not when from elsewhere in the code I call myWindow.Close(). Any ideas?

like image 254
Stephen Avatar asked Sep 30 '09 17:09

Stephen


2 Answers

Turns out the answer in this question solves the problem for me, too. It still seems strange, though, that the Unloaded event isn't getting fired. Go figure.

like image 173
Stephen Avatar answered Nov 07 '22 03:11

Stephen


In MyWindow class

this.Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing);   void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)         {             call User Control Method()          } 
like image 38
Srinivas Vinnakota Avatar answered Nov 07 '22 03:11

Srinivas Vinnakota