如何在WPF中为工具栏按钮创建热键?

时间:2012-07-11 12:31:54

标签: .net wpf button hotkeys

在WPF中,您可以按如下方式创建一个按钮:

<Button Name="Foo" Content="_Foo" />

“F”前面的下划线将F键与Foo按钮相关联(并在“Foo”中的“F”下添加下划线)。

但是,在工具栏中:

<ToolBar>
    <Button Name="Foo" Content="_Foo" />
</ToolBar>

这只是创建一个带有文本'_Foo'的按钮,并且没有与之关联的热键。

是否有任何内置方法可以为工具栏按钮创建热键?

3 个答案:

答案 0 :(得分:3)

Buttons的ToolBar样式会关闭正常行为,但您可以通过将AccessText明确指定为Button的内容来强制它:

<ToolBar>
    <Button Name="Foo">
        <AccessText>_Foo</AccessText>
    </Button>
</ToolBar>

答案 1 :(得分:2)

在包含工具栏的窗口上使用InputBindings。具体来说,您将创建一些KeyBindings,如下所示:

<Window.InputBindings>
    <KeyBinding Modifiers="Control" Key="S" Command="{Binding SaveCommand}"/>
</Window.InputBindings>

它需要使用绑定到ICommand( 使用MVVM吗?)并将其放在Window上,确保快捷方式是“全局”,否则你必须担心什么有键盘焦点。在工具栏中,您通常会通过工具提示指示快捷方式:

<ToolBar>
    <Button ToolTip="Save (Ctrl+S)" Command="{Binding SaveCommand}">
</ToolBar>

答案 2 :(得分:0)

您似乎试图让工具栏控件执行不应该执行的操作 - 它将Focusable属性设置为False,因此不会接收键盘输入,因此不会通过键盘激活任何按钮。 您希望通过菜单项,工具栏按钮或键盘提供操作 - 转到Commands和InputBindings,如前所述。

相关问题