当用户从文件菜单中单击退出菜单项时,应该如何退出应用程序?

我试过:

this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();

还有很多其他的。没有什么工作。


当前回答

在xaml代码中,你可以调用一个预定义的SystemCommand:

Command="SystemCommands.MinimizeWindowCommand"

我认为这应该是首选的方式……

其他回答

private void _MenuExit_Click(object sender, RoutedEventArgs e)
{
   System.Windows.Application.Current.MainWindow.Close();
}

//Override the onClose method in the Application Main window

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    MessageBoxResult result =   MessageBox.Show("Do you really want to close", "",
                                          MessageBoxButton.OKCancel);
    if (result == MessageBoxResult.Cancel)
    {
       e.Cancel = true;
    }
    base.OnClosing(e);
}

这应该可以达到目的:

Application.Current.Shutdown();

如果你感兴趣,这里有一些我认为有用的额外材料:

申请详情。当前的

WPF应用程序生命周期

不应该有Application.ShutDown();或. exit()消息。

Application是一个静态类。它不指向当前应用程序。 你需要进入当前应用程序,然后像这样关闭它:

Application.Current.Shutdown();

如果你使用application . current . shutdown()来退出应用程序,你可能会得到一个System. current . shutdown()。调用线程不能访问该对象,因为它属于另一个线程。如果从不同的线程调用它。要解决这个问题,您可以像这样包装调用

Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());

Caliburn微调味

public class CloseAppResult : CancelResult
{
    public override void Execute(CoroutineExecutionContext context)
    {
        Application.Current.Shutdown();
        base.Execute(context);
    }
}

public class CancelResult : Result
{
    public override void Execute(CoroutineExecutionContext context)
    {
        OnCompleted(this, new ResultCompletionEventArgs { WasCancelled = true });
    }
}