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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1499477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:03:34  来源:igfitidea点击:

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

wpfeventsuser-controls

提问by Stephen

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 需要知道包含它的 Window 何时关闭,以便它可以终止线程。

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.

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

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

为了参考,这里是我的代码的一些相关部分。

MyWindow.xaml:

我的窗口.xaml:

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

MyControl.xaml:

我的控件.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.
}

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?

所以简单回顾一下,当我“手动”关闭窗口(alt-F4,单击红色的“X”等)时,上面的 UserControl_Unloaded() 方法被调用,但不是从我调用的代码中的其他地方调用myWindow.Close()。有任何想法吗?

采纳答案by Stephen

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

原来这个问题的答案也为我解决了这个问题。但是,Unloaded 事件没有被触发似乎仍然很奇怪。去搞清楚。

回答by Srinivas Vinnakota

In MyWindow class

在 MyWindow 类中

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


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

        }

回答by Ilya Khaprov

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

为什么不将处理程序连接到 window.Closed 事件?您的 UserControl 可以遍历 ui 树以查找窗口。