Skip to content

Request the close of the application

yvlawy edited this page Nov 18, 2017 · 5 revisions

Manage the close of a WPF application in MVVM

The request of the close can come from many sides:

  • click on the X on the left corner of the main Window,
  • By a ALT+F4 keys,
  • By clicking on a Quit/Exit menu application.

The MainWindow.cs:

public partial class MainWindow : Window
{
    /// <summary>
    /// Request the close of the window (and the app because its the main window).
    /// </summary>
    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
        // exec request close the window (and the app)
        ((MainVM)this.DataContext).RequestCloseWindowCmd.Execute(null);

        // if the user cancel the close of the window, cancel the operation : IsWindowClosing= False -> Cancel= True
        e.Cancel = !((MainVM)this.DataContext).IsWindowClosing;
    }
    ...

The App.xaml is very light:

    <Application x:Class="DevApp.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:DevApp"
         >
        ...

The App.xaml.cs:

    public App()
    {
       ...
        Application.Current.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
       ...