为什么会Window.Close事件传播? [英] Why would Window.Close event propagate?
问题描述
我遇到了一个奇怪的情况下的子窗口的关闭
事件传播到父窗口,并导致它关闭为好。
I ran into a weird case where Close
event of the child window propagate to the parent window and causes it to close as well.
我做了一个最小的例子如下图所示。
I made a minimum example as shown below
有关 TestWindow
并没有什么,但
和 App.xaml.cs
我通过VS默认生成的WPF窗口覆盖 OnStartup
事件,并把它作为一个自定义的主
函数
and in App.xaml.cs
I override the OnStartup
event and use it as a custom Main
function
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
TestWindow t = new TestWindow();
t.ShowDialog();
}
现在,如果你点击X按钮关闭TestWindow,应用程序关闭而不是显示主窗口
。如果您注释掉 t.ShowDialog
那么主窗口
将显示就好了。接下来,如果你听主窗口
的结束
事件中,你会发现它会在 TestWindow
关闭这看起来不正确对我
Now if you click on the X button to close TestWindow, the application shuts down instead of showing the MainWindow
. If you comment out t.ShowDialog
then the MainWindow
will show just fine. Next if you listen to the Closing
event of MainWindow
you will find that it will trigger after the TestWindow
closes which doesn't seem right to me
推荐答案
这不是真正的传播的,WPF运行你的第一个对话框,并在这一过程目前已没有进一步的窗户关闭通知。帖子WPF应用程序的戒烟后处理消息。在此期间您的代码已进行到显示的处理消息泵时,遇到退出消息,因此关闭窗口并终止您的应用程序进一步的窗口。
It's not actually propagating, WPF runs your first dialog and upon closing notices that the process has no further windows present. WPF posts an application quit message for later processing. In the meantime your code has proceeded to display a further window which when processing the message pump encounters the quit message and so closes the window and terminates your app.
调试日志:
信息:0:应用程序OnStartup
Information: 0 : App OnStartup
信息:0:新的主窗口
信息:0:主窗口关闭
信息:0:应用程序退出
Information: 0 : App exiting
要解决,你需要删除的StartupUri
,而是处理启动
事件。
To resolve, you need to remove the StartupUri
and instead handle the Startup
event.
变化:
<Application x:Class="WpfCloseProblem.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCloseProblem"
StartupUri="MainWindow.xaml"> ...
...为:
...to:
<Application x:Class="WpfCloseProblem.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCloseProblem"
Startup="Application_Startup">
然后丢弃在OnStartup代码,而是定义为启动处理程序:
Then discard the code on OnStartup and instead define a handler for Startup:
//protected override void OnStartup(StartupEventArgs e)
//{
// base.OnStartup(e);
//
// TestWindow t = new TestWindow();
// t.ShowDialog();
//}
private void Application_Startup(object sender, StartupEventArgs e)
{
var main = new MainWindow();
TestWindow t = new TestWindow();
t.ShowDialog();
main.Show();
}
以前我是可以确认的对话框关闭后,主窗口
创建;装载和快速连续关闭。
Previously I was able to confirm that after the dialog closed, MainWindow
was created; loaded and closed in quick succession.
这篇关于为什么会Window.Close事件传播?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!