我最好的猜测是如何处理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事件
发布评论