Arne_22
Arne_22

Reputation: 57

Keep Application running after Closing Event in WPF

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

Answers (2)

thatguy
thatguy

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

simon at rcl
simon at rcl

Reputation: 7344

Two things:

  • To cancel the shutdown, set e.Cancel = true; and that's it.
  • If you're OK for it to shutdown, just let the code exit the method without setting the Cancel property. No need to call Shutdown();

Upvotes: 0

Related Questions