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" />
1: <MenuItem Header="_Open" InputGestureText="Ctrl + O" />
#Using CommandBindings - - I found this way is better and easier one
- 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" />
- 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
- 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)
Happy WPF Programming :)
Working with menu items for shortcuts in C#.NET
ReplyDelete