I want to implement Keyboard shortcuts for a MenuItem
. I have used the code below:
<MenuItem Header="_New" InputGestureText="CTRL+N" Click="NewMenu_Click">
<MenuItem.Icon>
<Image Source= "Images\NEW.PNG" Width="25" Height="28" />
</MenuItem.Icon>
</MenuItem>`
But the InputGestureText
property is not responding when I pressed the CTRL+N
. I am using Visual Studio Express Edition 2010. Am I missing anything here?
It is quite explicit in the documentation for the property:
This property does not associate the input gesture with the menu item; it simply adds text to the menu item. The application must handle the user's input to carry out the action. For information on how to associate a command with a menu item, see Command.
The best way to do this is to make a Command
, and associate the InputGesture
with that command:
public static class Commands
{
public static readonly RoutedCommand CreateNew = new RoutedCommand("New", typeof(Commands));
static Commands()
{
SomeCommand.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control));
}
}
...
// Wherever you want to create the MenuItem. "local" should be the namespace that
// you delcared "Commands" in.
<MenuItem Header="_New" Command="{x:Static local:Commands.CreateNew}">
...
// Wherever you want to process the command. I am assuming you want to do it in your
// main window, but you can do it anywhere in the route between your main window and
// the menu item.
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:Commands.CreateNew}"> Executed="CreateNew_Executed" />
</Window.CommandBindings>
...
// In the code behind for your main window (or whichever file you put the above XAML in)
private void CreateNew(object sender, ExecutedRoutedEventArgs e)
{
...
}
If you really just want a "New" command, you can skip creating the RoutedCommand
and InputGesture
, because that command is already created for you:
<MenuItem Header="_New" Command="New">
...
<Window.CommandBindings>
<CommandBinding Command="New" Executed="New_Executed" />
</Window.CommandBindings>
...
private void New_Executed(object sender, ExecutedRoutedEventArgs e)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With