定义菜单项快捷方式 [英] Defining MenuItem Shortcuts
问题描述
我需要一种简单的方法来设置菜单项的快捷方式.
但这不适用于快捷方式,只需单击即可:
我使用的是 WPF 4.0
您需要使用 KeyBindings
(和 CommandBindings
如果您(重新)使用 RoutedCommands
,例如在 ApplicationCommands
类)用于快捷方式应该工作的控件.
例如
<CommandBinding Command="New" Executed="CommandBinding_Executed"/></Window.CommandBindings><Window.InputBindings><KeyBinding Key="N" Modifiers="Control" Command="New"/></Window.InputBindings>
对于自定义RoutedCommands
:
静态类自定义命令{公共静态路由命令 DoStuff = 新路由命令();}
用法:
<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>...</窗口>
(实现ICommand
interface 而不是使用 RoutedCommands
.你可以有一个构造函数,它接受 Execute
和 CanExecute
的委托为了轻松创建执行不同操作的命令,此类实现通常称为 DelegateCommand
或 RelayCommand
.这样您就不需要 CommandBindings
.)>
I need a simple way to set a shortcut for menu items.
But this don´t work with shortcut, just with click:
<MenuItem Header="Editar">
<MenuItem Header="Procurar" Name="MenuProcurar"
InputGestureText="Ctrl+F"
Click="MenuProcurar_Click">
<MenuItem.ToolTip>
<ToolTip>
Procurar
</ToolTip>
</MenuItem.ToolTip>
</MenuItem>
</MenuItem>
I am using WPF 4.0
You need to use KeyBindings
(and CommandBindings
if you (re)use RoutedCommands
such as those found in the ApplicationCommands
class) for that in the 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 can have a constructor which takes delegates for Execute
and CanExecute
to easily create commands which do different things, such implementations are often called DelegateCommand
or RelayCommand
. This way you do not need CommandBindings
.)
这篇关于定义菜单项快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!