Click here to Skip to main content
15,894,540 members
Articles / Desktop Programming / WPF

Closing Windows and Applications with WPF and MVVM

Rate me:
Please Sign up or sign in to vote.
4.68/5 (13 votes)
10 Aug 2012CPOL12 min read 222.7K   5.8K   66  
This article samples a MVVM conform implementation of startup and shutdown sequences for an application and its dialogs.
namespace DialogCloser
{
  using System;
  using System.Windows;
  using System.Windows.Input;

  using View;
  using ViewModel;
  using DialogCloser.Service;
  using DialogCloser.Service.WindowViewModelMapping;

  /// <summary>
  /// Interaction logic for App.xaml
  /// </summary>
  public partial class App : Application
  {
    private bool mRequestClose = false;
    private MainWindow win = null;

    /// <summary>
    /// Initialize the RoutedCommand binding between MainWindow View and ViewModel
    /// </summary>
    /// <param name="win"></param>
    public void InitMainWindowCommandBinding(Window win)
    {
      win.CommandBindings.Add(new CommandBinding(AppCommand.Exit,
      (s, e) =>
      {
        e.Handled = true;

        ((AppViewModel)win.DataContext).ExitExecuted();
      }));

      win.CommandBindings.Add(new CommandBinding(AppCommand.ShowDialog,
      (s, e) =>
      {
        ((AppViewModel)win.DataContext).ShowUserNameDialog();

        e.Handled = true;
      }));

      win.CommandBindings.Add(new CommandBinding(AppCommand.NavigateBrowserTo,
      (s, e) =>
      {
        if (e != null)
          AppCommand.NavigateTo(e.Parameter);

        e.Handled = true;
      }));
    }

    private void Application_Startup(object sender, StartupEventArgs e)
    {
      // Configure service locator
      ServiceLocator.RegisterSingleton<IDialogService, DialogService>();
      ServiceLocator.RegisterSingleton<IWindowViewModelMappings, WindowViewModelMappings>();

      AppViewModel tVM = new AppViewModel();  // Construct ViewModel and MainWindow
      this.win = new MainWindow();

      tVM.OnSessionEnding = this.OnSessionEnding;

      this.win.Closing += this.OnClosing;

      // When the ViewModel asks to be closed, it closes the window via attached behaviour.
      // We use this event to shut down the remaining parts of the application
      tVM.RequestClose += delegate
      {
        // Make sure close down event is processed only once
        if (this.mRequestClose == false)
        {
          this.mRequestClose = true;

          // Save session data and close application
          this.OnClosed(this.win.DataContext as ViewModel.AppViewModel, this.win);
        }
      };

      this.win.DataContext = tVM; // Attach ViewModel to DataContext of ViewModel
      this.InitMainWindowCommandBinding(this.win);  // Initialize RoutedCommand bindings
      this.win.Show(); // SHOW ME DA WINDOW!
    }

    /// <summary>
    /// This executes when Windows is 'forced' to shut down the application.
    /// We can either tell Windows to wait (cancel App shutdown) or get out of its way.
    /// 
    /// See http://msdn.microsoft.com/en-us/library/system.windows.application.sessionending.aspx for details
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
    {
      e.Cancel = this.OnSessionEnding();
    }

    /// <summary>
    /// Determine whether Application MainWindow is ready to close down or
    /// whether close down should be cancelled - and cancel it.
    /// 
    /// This event is typically raised when the user clicks the window close button.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
    {
      e.Cancel = this.OnSessionEnding();
    }

    /// <summary>
    /// Evaluate whether application is ready to shutdown and print a corresponding message if not.
    /// </summary>
    /// <returns></returns>
    private bool OnSessionEnding()
    {
      ViewModel.AppViewModel tVM = this.MainWindow.DataContext as ViewModel.AppViewModel;

      if (tVM != null)
      {
        if (tVM.IsReadyToClose == false)
        {
          MessageBox.Show("Application is not ready to exit.\n" +
                          "Hint: Check the checkbox in the MainWindow before exiting the application.",
                          "Cannot exit application", MessageBoxButton.OK);

          return !tVM.IsReadyToClose; // Cancel close down request if ViewModel is not ready, yet
        }

        //tVM.OnRequestClose(false);

        return !tVM.IsReadyToClose; // Cancel close down request if ViewModel is not ready, yet
      }

      return true;
    }

    /// <summary>
    /// Execute closing function and persist session data here.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnClosed(ViewModel.AppViewModel appVM, Window win)
    {
      try
      {
        Console.WriteLine("Closing down apllication.");
      }
      catch (System.Exception exp)
      {
        MessageBox.Show(exp.ToString(), "Error in OnClosed method", MessageBoxButton.OK, MessageBoxImage.Error);
      }
    }
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
The Windows Presentation Foundation (WPF) and C# are among my favorites and so I developed Edi

and a few other projects on GitHub. I am normally an algorithms and structure type but WPF has such interesting UI sides that I cannot help myself but get into it.

https://de.linkedin.com/in/dirkbahle

Comments and Discussions