把RoutedUICommand放在MenuItem上简直就是太方便了。菜单项的快捷键(MenuItem.InputGestureText属性)会自动显示,而且菜单项的显示文字(MenuItem.Header属性)是RoutedUICommand.Text而不是Name属性。而相比其他命令源(ICommandSource接口),Button类型和Hyperlink类型就没这么方便了。
比如注册一个自定义的RoutedUICommand,Name是MyCommand,Text是我的命令,快捷键是Ctrl+Shift+M,下面命令注册代码:
public class MyCommands { public static RoutedUICommand MyCommand = new RoutedUICommand("我的命令", "MyCommand", typeof(MyCommands), new InputGestureCollection(new InputGesture[] { new KeyGesture(Key.M, ModifierKeys.Control | ModifierKeys.Shift) })); }
XAML:
<StackPanel xmlns:loc="clr-namespace:Mgen_WPF"> <Menu> <MenuItem Header="菜单"> <MenuItem Command="{x:Static loc:MyCommands.MyCommand}"/> </MenuItem> </Menu> <Button Command="{x:Static loc:MyCommands.MyCommand}"/> <TextBlock> <Hyperlink Command="{x:Static loc:MyCommands.MyCommand}"/> </TextBlock> </StackPanel>
结果,Button和Hyperlink的内容都不会自动出现:
而菜单项却显示得很完整:
RouteUICommand.Text会对应MenuItem.Header。
RoutedUICommand.InputGestures会对应MenuItem.InputGestureText。
不过默认对应的InputGestureText可能不适合中文,比如这样定义KeyGesture:
new KeyGesture(Key.Enter, ModifierKeys.Control | ModifierKeys.Shift) }
结果会显示Return(英文中的回车):
此时可以修改KeyGesture的DisplayString属性:
new KeyGesture(Key.Enter, ModifierKeys.Control | ModifierKeys.Shift, "Ctrl + Shift + 回车")
结果:
:D
作者:Mgen
出处:www.cnblogs.com/mgen
原文:http://www.cnblogs.com/mgen/archive/2012/01/19/2327631.html