C# WPF How to close a new window correctly?

百般思念 提交于 2020-02-23 14:47:20

问题


I have a simple question:

  1. Create a new WPF project, there's startup window in it(MainWindow.xaml).
  2. in this project, create a new Window(Window1.xaml)
  3. Windows1's loaded event, let it close:

    private void Window_Loaded(object sender, RoutedEventArgs e) { this.Close(); }

  4. put a "Open" button to MainWindow, implement it's click event:

    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.

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'. 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?


回答1:


In the App.xaml set:

ShutdownMode="OnMainWindowClose"

This must solve the problem. I recommend reading this question.




回答2:


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:

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.

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. It's also fine if I run the .exe without debugging.

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.



来源:https://stackoverflow.com/questions/42080966/c-sharp-wpf-how-to-close-a-new-window-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!