Handling the window closing event with WPF / MVVM Light Toolkit

Viewed 223950

I'd like to handle the Closing event (when a user clicks the upper right 'X' button) of my window in order to eventually display a confirm message or/and cancel the closing.

I know how to do this in the code-behind: subscribe to the Closing event of the window then use the CancelEventArgs.Cancel property.

But I'm using MVVM so I'm not sure it's the good approach.

I think the good approach would be to bind the Closing event to a Command in my ViewModel.

I tried that:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <cmd:EventToCommand Command="{Binding CloseCommand}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

With an associated RelayCommand in my ViewModel but it doesn't work (the command's code is not executed).

13 Answers

You could easily do it with some code behind; In Main.xaml set: Closing="Window_Closing"

In Main.cs:

 public MainViewModel dataContext { get; set; }
 public ICommand CloseApp 
   {
      get { return (ICommand)GetValue(CloseAppProperty); }
      set { SetValue(CloseAppProperty, value); }
   }
public static readonly DependencyProperty CloseAppProperty =
DependencyProperty.Register("CloseApp", typeof(ICommand), typeof(MainWindow), new PropertyMetadata(null));

In Main.OnLoading:

dataContext = DataContext as MainViewModel;

In Main.Window_Closing:

   if (CloseApp != null)
      CloseApp .Execute(this);

In MainWindowModel:

    public ICommand CloseApp => new CloseApp (this);

And finally:

class CloseApp : ICommand { public event EventHandler CanExecuteChanged;

    private MainViewModel _viewModel;

    public CloseApp (MainViewModel viewModel)
    {
        _viewModel = viewModel;
    }


    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        Console.WriteLine();
    }
}
Related