How to: Create a Menu with Keyboard Shortcuts

This example shows how to create a Menu that has MenuItem elements with specified keyboard shortcuts.

Keyboard shortcuts are character combinations that can be entered with the keyboard to invoke Menu commands. For example, the shortcut for Copy is Ctrl+C. There are two properties to use with keyboard shortcuts and MenuItem controls — the InputGestureText or Command property.

The following Extensible Application Markup Language (XAML) and C# examples show how to use the InputGestureText property to assign keyboard shortcuts text to a MenuItem. The following example assigns Ctrl+X for the Cut command. This only places the keyboard shortcut in the menu item. It does not associate the command with the MenuItem. The application must handle the user's input to carry out the action.

Example

<MenuItem Header="_Cut" InputGestureText="Ctrl+X"/>
<MenuItem Header="_Find" InputGestureText="Ctrl+F"/>
mia = new MenuItem();
mia.Header = "_Cut";
mia.InputGestureText = "Ctrl+X";
mi.Items.Add(mia);

The following XAML and C# examples show how to use the Command property to associate the Copy and Paste commands with a MenuItem. Not only does the command property associate a command with a MenuItem but it also supplies the input gesture text that a user enters to invoke the command.

<MenuItem Command="ApplicationCommands.Open">
<MenuItem.Header>_Open</MenuItem.Header>
</MenuItem>
<MenuItem Command="ApplicationCommands.Close">
<MenuItem.Header>_Close</MenuItem.Header>
</MenuItem>
mib = new MenuItem();
mib.Command = System.Windows.Input.ApplicationCommands.Copy;
mib.Header = "_Copy";
mi.Items.Add(mib);

mic = new MenuItem();
mic.Command = System.Windows.Input.ApplicationCommands.Paste;
mic.Header = "_Paste";
mi.Items.Add(mic);

For the complete sample see Menu Sample.

For information on how to use a command see How to: Enable a Command.and How to: Add a Command to a MenuItem.

See Also

Reference

Menu
MenuItem

Concepts

Menu Overview