Handling the window closing event with WPF / MVVM Light Toolkit Handling the window closing event with WPF / MVVM Light Toolkit wpf wpf

Handling the window closing event with WPF / MVVM Light Toolkit


I would simply associate the handler in the View constructor:

MyWindow() {    // Set up ViewModel, assign to DataContext etc.    Closing += viewModel.OnWindowClosing;}

Then add the handler to the ViewModel:

using System.ComponentModel;public void OnWindowClosing(object sender, CancelEventArgs e) {   // Handle closing logic, set e.Cancel as needed}

In this case, you gain exactly nothing except complexity by using a more elaborate pattern with more indirection (5 extra lines of XAML plus Command pattern).

The "zero code-behind" mantra is not the goal in itself, the point is to decouple ViewModel from the View. Even when the event is bound in code-behind of the View, the ViewModel does not depend on the View and the closing logic can be unit-tested.


This code works just fine:

ViewModel.cs:

public ICommand WindowClosing{    get    {        return new RelayCommand<CancelEventArgs>(            (args) =>{                     });    }}

and in XAML:

<i:Interaction.Triggers>    <i:EventTrigger EventName="Closing">        <command:EventToCommand Command="{Binding WindowClosing}" PassEventArgsToCommand="True" />    </i:EventTrigger></i:Interaction.Triggers>

assuming that:

  • ViewModel is assigned to a DataContext of the main container.
  • xmlns:command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL5"
  • xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"


This option is even easier, and maybe is suitable for you. In your View Model constructor, you can subscribe the Main Window closing event like this:

Application.Current.MainWindow.Closing += new CancelEventHandler(MainWindow_Closing);void MainWindow_Closing(object sender, CancelEventArgs e){            //Your code to handle the event}

All the best.