Like it

Sunday, July 17, 2011

WPF Menu - How to implement Shortcut Keys

WPF Menu - How to implement Shortcut Heys
There are many ways to add shortcut keys in WPF
# Using Underscore - In the Header Property, put the "_" before the Text, and you can use "ALT+<Key>". This is not Shortcut key, it is normally called "HotKey"

   1:  <MenuItem Header="_Open" /> 
# Using InputGestureText - This is the way Visual Studio gives directly. - You can set a Key combination directly over here. 

   1:  <MenuItem Header="_Open" InputGestureText="Ctrl + O" /> 
But it will invoke the click event, even if we use the Key combination. This is for display purpose only.
#Using CommandBindings - - I found this way is better and easier one
  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.
       1:  Sub CommandExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
       2:  'Add the commands to be executed.
       3:  If e.Command.Equals(ApplicationCommands.Open) Then
       4:  MessageBox.Show("Open Menu item clicked")
       5:  ElseIf e.Command.Equals(ApplicationCommands.Close) Then
       6:  MessageBox.Show("Close menu item clicked")
       7:  End If
       8:  End Sub
       9:  Sub CommandCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
      10:  e.CanExecute = True 'I am always returning true, based on this the menu item will enabled / disabled
      11:  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)
menu_shortcuts_in_wpf
Happy WPF Programming :)

1 comment: