0

In WPF, you can make a button as follows:

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

The underscore before the 'F' associates the F key with the Foo button (and adds an underline under the 'F' in 'Foo').

However, in a toolbar:

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

This just creates a button with the text '_Foo' and no hotkey is associated with it.

Is there any built-in way to create a hotkey for a toolbar button?

Matt
  • 21,026
  • 18
  • 63
  • 115
  • Have a look at the first answer here: http://stackoverflow.com/questions/1361350/keyboard-shortcuts-in-wpf – Zak Jul 11 '12 at 12:56

3 Answers3

4

Use InputBindings on the Window containing the Toolbar. Specifically, you will create some KeyBindings like so:

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

It requires using a binding to an ICommand (you are using MVVM right?) and by putting it on the Window you ensure that the shortcut is "global", otherwise you have to worry about what has keyboard focus. In your toolbar, you'll indicate the shortcut by a Tooltip generally:

<ToolBar>
    <Button ToolTip="Save (Ctrl+S)" Command="{Binding SaveCommand}">
</ToolBar>
Sean Hanley
  • 5,677
  • 7
  • 42
  • 53
  • I was looking for a way to create a hotkey not a key binding. – Matt Jul 11 '12 at 13:02
  • 1
    Maybe you should expand your question to specify exactly what you mean by "hotkey"? – Sean Hanley Jul 11 '12 at 13:05
  • 1
    If you would like to know what a hotkey is, open up some basic Windows program (Calculator is a good example). Then press ALT. You will notice that focus switched to the menu bar and one letter in each menu item is underlined. Pressing the underlined character jumps straight to that menu element. If you open up a menu, you will notice that the elements there also have underlined letters. These underlined letters are known as hotkeys as opposed to keyboard shortcuts. You may notice some of the menu items additionally have a keyboard shortcut bound. – Matt Jul 11 '12 at 13:13
3

The ToolBar style for Buttons turns off the normal behavior but you can force it back by explicitly specifying the AccessText as the Button's Content:

<ToolBar>
    <Button Name="Foo">
        <AccessText>_Foo</AccessText>
    </Button>
</ToolBar>
John Bowen
  • 24,213
  • 4
  • 58
  • 56
0

You seem to be trying to make Toolbar control do what it is not supposed to do - it has Focusable property set to False thus does not receive keyboard input hence no button will ever be activated by means of keyboard. You want to have an action available by either menu item, toolbar button or keyboard - go for Commands and InputBindings, as suggested earlier.

Alex Seleznyov
  • 905
  • 6
  • 18