WPF Window.Close() 未触发 UserControl.Unloaded 事件事件、Window、WPF、Close

2023-09-07 14:51:15 作者:就是懒

我有一个包含自定义用户控件的窗口.UserControl 需要知道包含它的 Window 何时关闭,以便终止线程.

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.

我对如何实现这一点的最佳猜测是处理 UserControl 的 Unloaded 事件.但是,Unloaded 事件似乎只在用户实际单击以关闭窗口时触发,而不是在我以编程方式在窗口上调用 Close() 方法时触发.

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:

MyWindow.xaml:

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

MyControl.xaml:

MyControl.xaml:

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

MyControl.xaml.cs:

MyControl.xaml.cs:

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

所以回顾一下,上面的 UserControl_Unloaded() 方法在我手动"关闭窗口时被调用(alt-F4,点击红色的X"等),但不是从代码中的其他地方调用 myWindow.Close().有什么想法吗?

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?

推荐答案

在这个问题中得到了答案 也为我解决了这个问题.不过,Unloaded 事件没有被触发似乎仍然很奇怪.去图吧.

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.