是的,如果微软在其预定义命令集合中包括了一个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">
<Separator/>
<MenuItem Command="{StaticResource fileExitCommand}"/>
</MenuItem>
</Menu>
</DockPanel>
</Window>
< p > 命令绑定的
Executed
事件处理程序很简单:
private void fileExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
Close();
}
假设你的程序实现采用通常语义,通过关闭主窗口来退出程序。
这种方式,所有与用户界面相关的元素都直接进入 RoutedUICommand 对象,可以在 XAML 中正确方便地配置该对象,而无需声明新的 C# 类以实现命令并/或混乱地在代码后台中进行输入绑定。菜单项对象已经知道如何显示 RoutedUICommand,因此采用这种方法可将命令属性与其余用户界面分离开。它还提供了一种方便的方法来提供第二个键盘手势,以防您希望使用除默认的 Alt + F4 之外的其他内容(例如 Ctrl + W)。
您甚至可以将 RoutedUICommand 声明放在 App.xaml 文件中,以便在程序中的多个窗口中重复使用。再次将 UI 特定方面(在资源中声明)与程序中找到的使用者分离开。
我发现这种方法比其他我见过的方法更具普适性和易于实现(包括本文和其他地方)。