如何通过上下文菜单关闭WPF应用程序?

7

在WPF中,是否有一个命令可以从上下文菜单关闭应用程序?也就是说,在任何窗口的标题栏上右键单击时得到的相同上下文菜单?

有许多标准命令,但我无法找到退出命令。

4个回答

16

很遗憾,这并不存在。您需要实现自定义命令并调用它。

Application.Current.Shutdown();

3
很可能是 Application.Current.Shutdown();,因为 Application.Current.Exit(); 是一个事件。 - Vitalij

1

你的问题已经解决了。但是以下代码可能会帮助到其他人。

     Environment.Exit(0)

我认为应该使用Application.Current.Shutdown。如果我没记错,Env.Exit相当于直接杀死进程,是一种相当严厉的操作。但我可能完全错了。不幸的是,我手头没有反编译工具来验证它。 - quetzalcoatl
使用 Environment.Exit(0) 关闭应用程序是一种非常粗暴的方式。它会释放应用程序的所有资源并返回操作系统环境。 - Towhid

1

有一个 ApplicationCommands.Close,但没有 ApplicationCommands.Exit。

请参见 此线程(例如)以找到替代方法(如创建自定义命令)。


0

其实并不是很复杂(但微软却没有提供它,真是糟糕)。这是你需要的:

public static class MyCommands
{
    private static readonly ICommand appCloseCmd = new ApplicationCloseCommand();
    public static ICommand ApplicationCloseCommand
    {
        get { return appCloseCmd; }
    }
}

//===================================================================================================
public class ApplicationCloseCommand : ICommand
{
    public event EventHandler CanExecuteChanged
    {
        // You may not need a body here at all...
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter)
    {
        return Application.Current != null && Application.Current.MainWindow != null;
    }

    public void Execute(object parameter)
    {
        Application.Current.MainWindow.Close();
    }
}

而且,AplicationCloseCommand.CanExecuteChanged 事件处理程序的主体甚至可能不需要。

您可以这样使用它:

<MenuItem Header="{DynamicResource MenuFileExit}" Command="MyNamespace:MyCommands.ApplicationCloseCommand"/>

干杯!

(你无法想象我自己发现这个命令需要多长时间...)


1
Resharper告诉我的小技巧:MyCommands类的完整主体如下:public static ICommand ApplicationCloseCommand { get; } = new ApplicationCloseCommand(); - Olle Kelderman
@OlleKelderman 是的,这是C# 6版本的语法。那个答案是在它之前的。 :) - NoOne
我知道,对于通过搜索引擎来到这里的任何人仍然是有用的 :) - Olle Kelderman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接