dotnet thoughts 

a dotnet developer's technical blog

Shortcuts keys in WPF Menu

From the last few days I was searching for adding shortcut keys to WPF menu items. I didn’t see any direct method over there in Visual Studio. But after some googling I found some ways.

  1. Using access keys, like ALT+key – This is like the old Hot key implementation, using &, but & will not work in WPF instead of this we need to use “_”
    <MenuItem Header="_Open" />
    But these way you can use ALT+ key as the shortcut key
  2. Using code, like for displaying the shortcut key in the Menu item you can use “InputGestureText”e; property of menu item and using the code, need to capture the key press. I don’t know is it possible or not, I wasn’t checked this method, but the shortcut will appear on the menu :)
    <MenuItem Header="_Open" InputGestureText="Ctrl+O" />
  3. The final way is using CommandBindings. I found this way is better compare to the previous methods, and it is an easy way.
    1. In the markup create the command Bindings using Command Collections.
      <CommandBinding Command="ApplicationCommands.Open" CanExecute="CommandCanExecute" Executed="CommandExecuted" />
      <CommandBinding Command="ApplicationCommands.Close" CanExecute="CommandCanExecute" Executed="CommandExecuted" />
    2. In the code implement the event Handlers.
      Sub CommandExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
      'Add the commands to be executed.
      If e.Command.Equals(ApplicationCommands.Open) Then
      MessageBox.Show("Open Menu item clicked")
      ElseIf e.Command.Equals(ApplicationCommands.Close) Then
      MessageBox.Show("Close menu item clicked")
      End If
      End Sub
      Sub CommandCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
      e.CanExecute = True 'I am always returning true, based on this the menu item will enabled / disabled
      End Sub
    3. Assign the Commands to the Command property of our menu items. <MenuItem Command="ApplicationCommands.Open" >
      <Separator />
      <MenuItem Command="ApplicationCommands.Close" />

Compile it run it. You will see “Ctrl + O” added to the right side Open menu item.

You can see Ctrl + O added into the Open Menu item(Screenshot)

No Responses to “Shortcuts keys in WPF Menu”

  1. hejdig.

    The tag has to be surrounded by … like found in http://en.csharp-online.net/WPF_Concepts—Built-In_Commands

    Happy hacking!

    /OF

    Comment by LosManos — October 31, 2008 @ 11:23 pm

  2. hejdig.

    The tag CommandBinding has to be surrounded by Window.CommandBindings like found in http://en.csharp-online.net/WPF_Concepts—Built-In_Commands

    Happy hacking!

    /OF

    Comment by LosManos — October 31, 2008 @ 11:24 pm

RSS feed for comments on this post. TrackBack URL

Leave a Response

*