WPF Window.Close()不触发UserControl.Unloaded事件 [英] WPF Window.Close() not triggering UserControl.Unloaded event

查看:1754
本文介绍了WPF Window.Close()不触发UserControl.Unloaded事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含自定义UserControl的窗口。 UserControl需要知道何时包含它的窗口已关闭,以便它可以终止线程。



我最好的猜测是如何处理UserControl的卸载事件但是,当用户实际点击关闭窗口时,Unloaded事件似乎正在触发,但是当我以编程方式调用窗口上的Close()方法时,并不是这样。



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



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/>
<! - 东西 - >
< / UserControl>

MyControl.xaml.cs:

  void UserControl_Unloaded(object sender,RoutedEventArgs e)
{
//停止线程。
}

所以只是为了回顾一下,上面的UserControl_Unloaded()方法在我关闭窗口手动(alt-F4,点击红色的X等),但不是从代码中的其他地方调用 myWindow.Close() 。任何想法?

解决方案


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?

解决方案

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.

这篇关于WPF Window.Close()不触发UserControl.Unloaded事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆