【问题标题】:Keep Application running after Closing Event in WPF在 WPF 中关闭事件后保持应用程序运行
【发布时间】:2020-08-26 09:33:54
【问题描述】:

我已经为我的主应用程序Window.xaml 宣布了一个结束事件。在那里,我通过MessageBox 询问用户是否确定在不保存的情况下关闭应用程序,但无论消息框的结果如何,我的应用程序都会关闭。这里有什么问题?

闭幕活动代码:

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();
   }
}

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    如果你想阻止关闭,你必须将CancelEventArgs中的Cancel属性设置为true

    if (result == MessageBoxResult.No)
    {
       e.Cancel = true;
       dataContext.SaveAllVariables();
    } 
    

    Cancel 的默认值是false,所以应用程序在转义处理程序时无论如何都会关闭,您不必调用Shutdown();

    【讨论】:

      【解决方案2】:

      两件事:

      • 要取消关机,设置e.Cancel = true;就可以了。
      • 如果您可以关闭它,只需让代码退出该方法 不设置 Cancel 属性。无需调用 Shutdown();

      【讨论】:

        猜你喜欢
        • 2022-01-23
        • 1970-01-01
        • 2011-04-02
        • 1970-01-01
        • 2021-07-17
        • 1970-01-01
        • 1970-01-01
        • 2015-02-06
        • 1970-01-01
        相关资源
        最近更新 更多