Search code examples
wpfkeyboard-shortcuts

Defining MenuItem Shortcuts


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


Solution

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