How can I cancel exiting from particular form after Cancel button (or X at the top right corner, or Esc) was clicked?
WPF:
You are trying to do View's work in ViewModel class. Let your View class to handle the closing request and whether it should be canceled or not.
To cancel closing of a window you can subscribe to the Closing
event of view and set CancelEventArgs.Cancel
to true after showing a MessageBox
.
Here is an example:
Code behind:
private void OnClosing(object sender, CancelEventArgs e)
{
var result = MessageBox.Show("Really close?", "Warning", MessageBoxButton.YesNo);
if (result != MessageBoxResult.Yes)
{
e.Cancel = true;
}
// OR, if triggering dialog via view-model:
bool shouldClose = ((MyViewModel) DataContext).TryClose();
if(!shouldClose)
{
e.Cancel = true;
}
}