How can I cancel exiting from particular form after Cancel button (or X at the top right corner, or Esc) was clicked?
WPF:
I'm not an MVVM expert, but in my opinion Yusufs' answer isn't quite MVVM. On the other hand Torpederos answer is a bit complicated for only close cancellation. Here is my approach. In this example I subscribed to the closing event, but it is always cancelled
private void OnClosing(object sender, CancelEventArgs e)
{
e.Cancel = true;
return;
}
In the XAML I added this
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
And finally in the view model
public ICommand Close { get; set; }
Close = new RelayCommand(CommandClose);
private void CommandClose(object sender)
{
if (Dirty)
{
// Save your data here
}
Environment.Exit(0);
}
In this approach the the closing event is triggered first. That cancels the closing. After that the interaction trigger is invoked and triggers the code in the view model via the RelayCommand. In the view model I can use the Dirty flag that is not accessible in the view.