WPF App Doesn't Shut Down When Closing Main Window

后端 未结 6 1741
滥情空心
滥情空心 2020-12-01 02:22

I\'m used to WinForms programming in Visual Studio, but I wanted to give WPF a try.

I added another window to my project, called Window01. The main window is called

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 03:09

    I'm glad you got your answer but for the sake of others I'll answer your question as-well to add some information.


    Step 1

    First, if you want your program to exit when the main window closes down, you need to specify, since this is not WinForms where this behavior is default.

    (The default in WPF is when the last window closes down)

    In Code

    Go to your application instance in your entry point (In VS 2012's WPF program the default is nested inside App.xaml, so go inside it and navigate to App.xaml.cs & create a constructor).

    In the constructor specify that your Application's ShutdownMode should be ShutdownMode.OnLastWindowClose.

        public App()
        {
            ShutdownMode = ShutdownMode.OnLastWindowClose;
        }
    

    In XAML

    Go to your App.xaml file that VS 2012 created by default (or create it yourself) The root is an Application, specify inside that your Application's ShutdownMode should be ShutdownMode.OnLastWindowClose.

    
    

    If it works, you're done; you can stop reading.


    Step 2

    If the above didn't work (I guess you wrote the WPF application from scratch), the main window probably isn't known to the application as the main window. So specify that as-well.

    In Code

    Go to the application's constructor as you did in Step 1, and specify that Application.MainWindow's value is your Window:

    MainWindow = mainWindow;
    

    In XAML

    Go to the Application XAML as you did in Step 1, and specify that Application.MainWindow's value is your Window:

    MainWindow = "mainWindow";
    

    Alternative

    I don't think this is the best approach, just because WPF doesn't want you to do this (so it has Application's ShutdownMode), but you can just use an event / override an event method (OnEventHappened).

    Go to the MainWindow's code-behind file and add:

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
    
            App.Current.Shutdown();
        }
    

提交回复
热议问题