[英]C# WPF How to close a new window correctly?
I have a simple question:我有一个简单的问题:
1- Create a new WPF project, there's startup window in it: MainWindow.xaml
. 1- 创建一个新的 WPF 项目,其中有启动窗口:
MainWindow.xaml
。
2- In this project, create a new window Window1.xaml
. 2- 在这个项目中,创建一个新窗口
Window1.xaml
。
3- Windows1
's loaded event, let it close. 3-
Windows1
的加载事件,让它关闭。
4- Put an Open
button to MainWindow
. 4- 将一个
Open
按钮放到MainWindow
上。 Implement it's click event.实现它的点击事件。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Close();
}
private void button_Click(object sender, RoutedEventArgs e)
{
Window1 w = new Window1();
w.Show();
}
When I start this application, VS2015's UI became to the DEBUGING MODE
, then I click the close button on the right top corner of the Window, VS2015's UI back to normal mode.当我启动这个应用程序时,VS2015 的 UI 变成了
DEBUGING MODE
,然后我点击窗口右上角的关闭按钮,VS2015 的 UI 回到正常模式。
Now, if I start application, click Open
button, then Window1
will show quickly and closed, but, if I click the close button on the right top corner of MainWindow
, things different: VS2015 will no go back to normal mode but stay in DEBUGING MODE
.现在,如果我启动应用程序,单击“
Open
”按钮,然后Window1
将快速显示并关闭,但是,如果我单击MainWindow
右上角的关闭按钮,情况会有所不同:VS2015 将不会返回正常模式,而是停留在DEBUGING MODE
。 so to me, that means something hang there and I don't know what is it.所以对我来说,这意味着有东西挂在那里,我不知道它是什么。
Is there anyone know how to fix this problem?有谁知道如何解决这个问题?
This is not an answer, but just my findings of an actually interesting observation.这不是答案,而只是我的一个非常有趣的观察结果。 I did your test (opening and closing the Window) a couple times and then dumped the list of WPF windows:
我做了几次测试(打开和关闭窗口),然后转储了 WPF 窗口列表:
foreach (Window w in Application.Current.Windows)
Debug.WriteLine(w.GetType().FullName)
Resulting in:导致:
WpfTest.MainWindow
Microsoft.VisualStudio.DesignTools.WpfTap.WpfVisualTreeService.Adorners.AdornerLayerWindow
Microsoft.VisualStudio.DesignTools.WpfTap.WpfVisualTreeService.Adorners.AdornerLayerWindow
Microsoft.VisualStudio.DesignTools.WpfTap.WpfVisualTreeService.Adorners.AdornerLayerWindow
WpfTap
is Visual Studio's WPF debugger, that helps debug the WPF content tree. WpfTap
是 Visual Studio 的 WPF 调试器,可帮助调试 WPF 内容树。
Now, if instead of using the Loaded
event, I used the ContentRendered
event to close the window, it doesn't happen, and things work as normal.现在,如果我没有使用
Loaded
事件,而是使用ContentRendered
事件来关闭窗口,则不会发生这种情况,并且一切正常。 It's also fine if I run the.exe without debugging.如果我不调试就运行.exe 也可以。
So it seems like Visual Studio attaches the WPF debugger *after* a Window's Loaded
event, and if you close the window too early, it leaves the debugger component hanging around in memory.因此,看起来 Visual Studio *在* Window 的
Loaded
事件之后附加了 WPF 调试器,如果您过早关闭窗口,它会使调试器组件在内存中徘徊。
In the App.xaml set:在 App.xaml 集中:
ShutdownMode="OnMainWindowClose"
This must solve the problem.这必须解决问题。 I recommend reading this question .
我建议阅读这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.