views:

3215

answers:

3

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?

+1  A: 

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

Trickster
Not a bad idea. The solution I found in another SO question, though, seems a little cleaner. Not much, but a little.
Skinniest Man
What if the UserControl is removed before the window is closed? Resource leak!
Robert Jeppesen
A: 

A destructor..?

~MyControl()
{
    // Stop the thread
}
Trainee4Life
Bad idea. C# "destructors" (which are really finalizers) run when GC kills the object, which may happen very late in the game - worst case, on CLR shutdown. It's definitely not a replacement for `Unloaded`.
Pavel Minaev
Yep, indeed! My bad..
Trainee4Life
I've tried the destructor approach as well - it doesn't work. It never seems to be called if you put a breakpoint on it.
JasonD
+3  A: 

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.

Skinniest Man