我遇到了一个奇怪的情况Close
子窗口的事件传播到父窗口并导致其关闭。
我做了一个最小的例子,如下所示
For TestWindow
除了VS生成的默认WPF窗口之外什么都没有
and in App.xaml.cs
我覆盖OnStartup
事件并将其用作自定义Main
功能
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
TestWindow t = new TestWindow();
t.ShowDialog();
}
现在,如果单击 X 按钮关闭 TestWindow,应用程序将关闭,而不是显示MainWindow
。如果你评论出来t.ShowDialog
那么MainWindow
会显示得很好。接下来如果你听Closing
的事件MainWindow
你会发现它会在之后触发TestWindow
关闭,这对我来说似乎不合适
其实不是传播,WPF 运行您的第一个对话框,并在关闭时注意到该进程不再存在任何窗口。 WPF 发布应用程序quit消息以供稍后处理。与此同时,您的代码已继续显示另一个窗口,该窗口在处理消息泵时遇到退出消息,因此关闭该窗口并终止您的应用程序。
调试日志:
信息:0:应用程序启动时
信息:0:新的主窗口
信息:0:主窗口关闭
信息:0:应用程序退出
要解决此问题,您需要删除StartupUri
而是处理Startup
event.
Change:
<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 上的代码,并为 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();
}
以前我能够确认对话框关闭后,MainWindow
被创建;快速连续加载和关闭。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)