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

编程入门 行业动态 更新时间:2024-10-25 18:32:05
本文介绍了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事件

本文发布于:2023-11-09 15:32:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572739.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   Window   WPF   Close   Unloaded

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!