WPF App Doesn't Shut Down When Closing Main Window

后端 未结 6 1722
滥情空心
滥情空心 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条回答
  •  眼角桃花
    2020-12-01 03:09

    I stumbled across this Question when searching for something else and I was surprised that I could not see any of the proposed answers mentioning about Window.Owner.

        {
           var newWindow = new AdditionalWindow();
           newWindow.Owner = Window.GetWindow(this);
    
           // then later on show the window with Show() or ShowDialog()
        }
    

    A call to Window.GetWindow(this) is quite useful in View of an MVVM application when you are far down the visual tree not knowing where you have been instantiated, it can be called by supplying any FrameWork element (e.g. UserContol, Button, Page). Obviously if you have a direct reference to the window then use that or even Application.Current.MainWindow.

    This is quite a powerful relationship that has a number of useful benefits that you might not realise to begin with (assuming you have not specifically coded separate windows to avoided these relationships).

    If we call your main window MainWindow and the second window as AdditionalWindow then....

    1. Minimising the MainWindow will also minimise AdditionalWindow
    2. Restoring MainWindow will also restore AdditionalWindow
    3. Closing MainWindow will close AdditionalWindow, but closing AdditionalWindow will not close MainWindow
    4. AdditioanlWindow will never get "lost" under MainWindow, i.e. AffffditionalWindow always shows above MainWindow in the z-order if you used Show() to display it (quite useful!)

    One thing to note though, if you have this relationship, then the Closing event on the AdditionalWindow is not called, so you'd have to manually iterate over the OwnedWindows collection. e.g. Create a way to call each window via a new Interface, or base class method.

        private void MainWindow_OnClosing(object sender, CancelEventArgs e)
        {
            foreach (var window in OwnedWindows)
            {
                var win = window as ICanCancelClosing;  // a new interface you have to create
                e.Cancel |= win.DoYouWantToCancelClosing();
            }        
        }
    

提交回复
热议问题