参考:http://stackoverflow.com/questions/1361350/keyboard-shortcuts-in-wpf
参考:http://stackoverflow.com/questions/4682915/defining-menuitem-shortcuts
You need to use KeyBindings (and CommandBindings if you (re)use RoutedCommands such as those found in the ApplicationCommands class) for that inthe controls where the shortcuts should work.
e.g.
<Window.CommandBindings>
<CommandBinding Command="New" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Key="N" Modifiers="Control" Command="New"/>
</Window.InputBindings>
For custom RoutedCommands:
static class CustomCommands
{
public static RoutedCommand DoStuff = new RoutedCommand();
}
usage:
<Window
...
xmlns:local="clr-namespace:MyNamespace">
<Window.CommandBindings>
<CommandBinding Command="local:CustomCommands.DoStuff" Executed="DoStuff_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Key="D" Modifiers="Control" Command="local:CustomCommands.DoStuff"/>
</Window.InputBindings>
...
</Window>
(It is often more convenient to implement the ICommand interface rather than using RoutedCommands. You canhave a constructor which takes delegates for Execute and CanExecute to easily create commands which do different things, suchimplementations are often called DelegateCommand orRelayCommand. This wayyou do not need CommandBindings.)
MenuItem上显示快捷键:
<MenuItemHeader="{x:Static Prop:Resources.File_AddBookItemHeader}" InputGestureText="Ctrl+N"Command="local:CustomCommands.DoStuff" Foreground="Black"/>
也可以不用再xaml中声明keyBinding,而用代码:
static classCustomCommands
{
public staticRoutedCommand DoStuff = new RoutedCommand();
staticCustomCommands()
{
DoStuff.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control));
}
}
本文介绍如何在WPF应用程序中定义和使用快捷键,包括通过KeyBindings和CommandBindings实现自定义命令,以及如何在MenuItem中显示快捷键提示。
1706

被折叠的 条评论
为什么被折叠?



