Reputation: 57
I have declared a closing event for my main application Window.xaml
. In there, I am asking the user via MessageBox
if he is sure to close the application without saving or not, but no matter the result of the message box, my application shuts down anyway. What is the problem here?
Code of the closing event:
private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
var content = ((FrameworkElement)ReportGeneratorFrame.Content);
var dataContext = (ReportGeneratorViewModel)content.DataContext;
string msg = "Schließen ohne Zwischenspeichern?";
MessageBoxResult result =
MessageBox.Show(
msg,
"Speicherabfrage!",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (result == MessageBoxResult.Yes)
{
// If user doesn't want to save, close Application
System.Windows.Application.Current.Shutdown();
}
else
{
dataContext.SaveAllVariables();
}
}
Upvotes: 1
Views: 631
Reputation: 22129
You have to set the Cancel
property in CancelEventArgs
to true
if you want to prevent closing.
if (result == MessageBoxResult.No)
{
e.Cancel = true;
dataContext.SaveAllVariables();
}
The default value for Cancel
is false
, so the application will shutdown anyway when escaping your handler, you do not have to call Shutdown();
.
Upvotes: 1
Reputation: 7344
Two things:
e.Cancel = true;
and that's it.Upvotes: 0