定义MenuItem快捷方式 [英] Defining MenuItem Shortcuts

查看:86
本文介绍了定义MenuItem快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种简单的方法来设置菜单项的快捷方式.

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>

我正在使用WPF 4.0

I am using WPF 4.0

推荐答案

您需要使用 CommandBindings (如果您(重新)使用 RoutedCommands ,例如在 ApplicationCommands)中的快捷方式应该起作用的控件.

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.

例如

<Window.CommandBindings>
        <CommandBinding Command="New" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
        <KeyBinding Key="N" Modifiers="Control" Command="New"/>
</Window.InputBindings>

对于自定义RoutedCommands:

static class CustomCommands
{
    public static RoutedCommand DoStuff = new RoutedCommand();
}

用法:

<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>

(实现 ICommand接口而不是使用RoutedCommands.您可以有一个构造函数,该构造函数使用ExecuteCanExecute的委托来轻松创建执行不同功能的命令,此类实现通常称为DelegateCommand.这样,您就不需要CommandBindings.)

(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.)

这篇关于定义MenuItem快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆