是的,Microsoft 将ApplicationCommands.Exit 命令包含在他们的预定义命令集合中会很有意义。令我失望的是他们没有。但正如这个问题的答案所表明的那样,并非一切都丢失了。
对于缺少正确的ApplicationCommands.Exit 对象,有很多解决方法。但是,我觉得最没抓住重点。他们要么在视图模型中实现某些东西,对于严格来说是视图行为的东西(在某些情况下使用例如Application.Current.MainWindow! 进入视图对象图),要么他们编写一堆代码隐藏来执行 XAML 所做的事情非常好,更方便。
恕我直言,最简单的方法就是为窗口声明一个RoutedUICommand 资源,将其附加到命令绑定和菜单项,以连接所有部分。例如:
<Window x:Class="ConwaysGameOfLife.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<RoutedUICommand x:Key="fileExitCommand" Text="File E_xit">
<RoutedUICommand.InputGestures>
<KeyGesture >Alt+F4</KeyGesture>
</RoutedUICommand.InputGestures>
</RoutedUICommand>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource fileExitCommand}" Executed="fileExitCommand_Executed"/>
</Window.CommandBindings>
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<!-- other menu items go here -->
<Separator/>
<MenuItem Command="{StaticResource fileExitCommand}"/>
</MenuItem>
</Menu>
<!-- the main client area UI goes here -->
</DockPanel>
</Window>
命令绑定的Executed 事件处理程序很简单:
private void fileExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
Close();
}
当然,假设您的程序实现遵循关闭主窗口以退出程序的通常语义。
通过这种方式,所有特定于 UI 的元素都直接进入 RoutedUICommand 对象,可以在 XAML 中正确方便地进行配置,而不必声明一个新的 C# 类来实现命令和/或弄乱代码隐藏的输入绑定。 MenuItem 对象已经知道如何处理 RoutedUICommand 在显示方面,因此走这条路线可以很好地将命令的属性与 UI 的其余部分解耦。它还提供了一种方便的方式来提供辅助键手势,以防您更喜欢默认的 Alt+F4 以外的其他东西(例如 Ctrl+W)。
您甚至可以将RoutedUICommand 声明放在 App.xaml 文件中,以便在程序中的多个窗口之间重复使用(如果它们存在)。同样,将资源中声明的 UI 特定方面与整个程序中的消费者解耦。
我发现这种方法比我见过的其他选项(这里和其他地方)更通用和更容易实现。