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

编程入门 行业动态 更新时间:2024-10-25 16:21:44
本文介绍了WPF Window.Close() 未触发 UserControl.Unloaded 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含自定义用户控件的窗口.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.

更多推荐

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

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

发布评论

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

>www.elefans.com

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