30

How to assign short-cut key to a button in WPF?

Googling gave me the answer as to append _ instead of '&' in standard Winforms.

So after I have done as below :

<Button Name="btnHelp" Content="_Help"></Button> 

I did not find 'H' underlined.

That is first issue.

Second issue is that, how to execute that after pressing Alt + H at run-time. Say just to display a message box is sufficient for the example sake.

I am using C#, WPF

Thanks.

Morteza Azizi
  • 479
  • 5
  • 23

8 Answers8

61

This is kind of old, but I ran into the same issue today.
I found that the simplest solution is to just use an AccessText element for the button's content.

<Button Command="{Binding SomeCommand}">
    <AccessText>_Help</AccessText>
</Button>

When you press the Alt key, the 'H' will be underlined on the button.
When you press the key combination Alt+H, the command that is bound to the button will be executed.

http://social.msdn.microsoft.com/Forums/vstudio/en-US/49c0e8e9-07ac-4371-b21c-3b30abf85e0b/button-hotkeys?forum=wpf

jhenninger
  • 931
  • 7
  • 17
  • 5
    Exactly why one should always feel free to do a little "necromancing" here on SO. I find your solution very elegant. Thank you. – Barton Aug 15 '14 at 00:49
  • 16
    A little late to the party, but `` also does the trick. – Mike Eason May 13 '15 at 10:38
  • 1
    @MikeEason It's been a while since I wrote this answer, and I agree with you entirely. Either way works exactly the same, and the decision is up to the user. The MSDN page for [AccessText](https://msdn.microsoft.com/en-us/library/system.windows.controls.accesstext%28v=vs.110%29.aspx#exampleToggle) has an example that shows using either method. – jhenninger May 14 '15 at 21:32
  • This approach also resolved my loss of the shortcut key when I switched over to using a Window specific Style Resource for setting the appearance of the buttons that previously set the button text inside the tags with the underscore prefix. Thank you. – ClockEndGooner Sep 23 '18 at 15:01
48

Solution for key binding (+ button binding) with own commands:

The body of XAML file:

<Window.Resources>
    <RoutedUICommand x:Key="MyCommand1" Text="Text" />
    <RoutedUICommand x:Key="MyCommand2" Text="Another Text" />
</Window.Resources>

<Window.CommandBindings>
    <CommandBinding Command="{StaticResource MyCommand1}" 
                    Executed="FirstMethod" />
    <CommandBinding Command="{StaticResource MyCommand2}" 
                    Executed="SecondMethod" />
</Window.CommandBindings>

<Window.InputBindings>
    <KeyBinding Key="Z" Modifiers="Ctrl" Command="{StaticResource MyCommand1}" />
    <KeyBinding Key="H" Modifiers="Alt" Command="{StaticResource MyCommand2}" />
</Window.InputBindings>

<Grid>
    <Button x:Name="btn1" Command="{StaticResource MyCommand1}" Content="Click me" />
    <Button x:Name="btn2" Command="{StaticResource MyCommand2}" Content="Click me" />
</Grid>

and .CS file:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    public void FirstMethod(Object sender, ExecutedRoutedEventArgs e)
    {
        // btn1
    }

    public void SecondMethod(Object sender, ExecutedRoutedEventArgs e)
    {
        // btn2
    }
}
yurislav
  • 1,119
  • 12
  • 17
  • 8
    Thanks... but... I don't suppose this could be done without having to edit the XAML in four different places every time one wants a single keyboard shortcut? – Qwertie Apr 10 '13 at 19:16
  • Just to save someone else some pain - make sure the `Window.Resources` comes BEFORE the `Window.CommandBindings/InputBindings`. Otherwise, you will definitely run into a runtime problem about it not being able to find the resource. – jep Nov 11 '13 at 02:46
  • 1
    All I needed here was the `` section, and bound each `KeyBinding` to an `ICommand` property in my view model. – Eric Sondergard May 18 '17 at 08:25
  • The answer was written with the assumption that MVVM pattern is not used at all. – yurislav May 18 '17 at 09:35
4

The shortcut is just h for your sample code. On

To initially show underlines for shortcuts is a Windows setting and not controlled by an app. In Windows XP, go to Display Properties -> Appearance -> Effects and you will see a checkbox labeled "Hide underlined letters for keyboard navigation until I press the Alt key". For Vista/Win7 I think they moved that setting somewhere else.

Wallstreet Programmer
  • 9,567
  • 3
  • 37
  • 52
3

The simplest solution I've found is to stick a label inside the button:

<Button Name="btnHelp"><Label>_Help</Label></Button> 
Daniel Crowe
  • 321
  • 3
  • 9
3

To bind keyboard gestures, you need to use the KeyGestures with commands. Check out commands for more information on this. Also there are loads of predefined commands which can directly be used in your application (like, Cut, Copy, Paste, Help, Properties, etc.,).

Community
  • 1
  • 1
sudarsanyes
  • 3,156
  • 8
  • 42
  • 52
0

This is kind of old, but I ran into the same issue today. I found that the simplest solution is to just use an hidden element for the shortcut key.

<Button x:Name="b2" Click="Button_Click">
    <Button.Content>
        <StackPanel Orientation="Horizontal">
            <Label Width="0" Height="0">_H</Label>
            <TextBlock>
                <Underline>H</Underline>elp
            </TextBlock>
        </StackPanel>
    </Button.Content>
</Button>
0

You can use Window.InputBinding if you are using commands like me (For MVVM).

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

        <KeyBinding Key="V"
                    Modifiers="Ctrl"
                    Command="{Binding TimeLogCommand}" /> 
</Window.InputBindings>
Gururaj
  • 157
  • 9
0

My issue was that I was binding the button content and adding the "_" in the property just resulted in "_Do X" instead of the actual shortcut. @jhenninger answer solved my issue.

<AccessText Text="{Binding LogButtonContent, FallbackValue=_View Log}" Margin="10,0,10,0"/>
Steve S
  • 21
  • 4