Search code examples
c#wpfshortcutroutedcommand

WPF menus with shortcuts and custom RoutedCommand


Im new to WPF so i might be missing something. I have a simple function in my MainWindow class called StartService. I wanted to add a menu item "Start Service" with a shortcut Ctrl+S to my application. I had to do the following:

  1. In my MainWindow class i had to define:

    public static RoutedCommand StartServiceRoutedCmd = new RoutedCommand();

  2. In my XAML code i added:

<MenuItem Header="_Start Service" InputGestureText="Ctrl+S" Click="OnStartService" />

<Window.CommandBindings>
    <CommandBinding Command="{x:Static loc:MainWindow.StartServiceRoutedCmd}" 
                    Executed="OnStartService" />
</Window.CommandBindings>

<Window.InputBindings>
    <KeyBinding Command="loc:MainWindow.StartServiceRoutedCmd" Gesture="CTRL+S" />
</Window.InputBindings>

Things are working. I'm wondering if this is the correct and organized way to go? I am gonna need a shortcut for my StopService function. Does this mean i will need to define a new RoutedCommand StopServiceRoutedCmd, and so on for every shortcut i need?


Solution

  • <MenuItem Header="_Start Service" InputGestureText="Ctrl+S" Command="loc:MainWindow.StartServiceRoutedCmd />
    
    <Window.CommandBindings>
           <CommandBinding Command="{x:Static loc:MainWindow.StartServiceRoutedCmd}" 
                    Executed="OnStartService" />
           </Window.CommandBindings>
    
    <Window.InputBindings>
           <KeyBinding Command="loc:MainWindow.StartServiceRoutedCmd" Gesture="CTRL+S" />
    </Window.InputBindings>