29

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Stephen
  • 3,515
  • 5
  • 27
  • 33

3 Answers3

13

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.

Community
  • 1
  • 1
Stephen
  • 3,515
  • 5
  • 27
  • 33
  • 6
    From the documentation: Note that the Unloaded event is not raised after an application begins shutting down. Application shutdown occurs when the condition defined by the ShutdownMode property occurs. If you place cleanup code within a handler for the Unloaded event, such as for a Window or a UserControl, it may not be called as expected. – Mike Post Nov 18 '10 at 22:24
2

In MyWindow class

this.Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing);


void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            call User Control Method()

        }
Andro Selva
  • 53,910
  • 52
  • 193
  • 240
1

Why just not connect handler to the window.Closed event? Your UserControl can walk through ui tree to find the window.

Ilya Khaprov
  • 2,546
  • 14
  • 23
  • Not a bad idea. The solution I found in another SO question, though, seems a little cleaner. Not much, but a little. – Stephen Sep 30 '09 at 19:53
  • 4
    What if the UserControl is removed before the window is closed? Resource leak! – Robert Jeppesen Nov 12 '09 at 15:14
  • >" The solution I found in another SO question, though, seems a little cleaner. Not much, but a little." What did you see?? https://xkcd.com/979/ – Ryan Leach Sep 14 '18 at 06:19