问题
I already have the following:
var myContextMenu = new System.Windows.Controls.ContextMenu();
var exitItem = new MenuItem();
exitItem.Header = "E_xit";
exitItem.Item.Click += new RoutedEventHandler(new System.EventHandler(ExitProgram));
myContextMenu.Items.Add(exitItem);
This causes my context menu to display the Exit menu item, with an underlined "x". However, pressing x does nothing. Clicking the menu item works fine.
How can I associate an event with the x key? Please note that this has to be done programmatically in my context. I cannot compose this solution in the XAML in front.
回答1:
The usual way to add shortcuts is as follows:
var exitCommand = new RelayCommand(_ => ExitProgram());
var exitItem = new MenuItem();
exitItem.Header = "E_xit";
exitItem.Command = exitCommand;
myContextMenu.Items.Add(exitItem);
InputBindings.Add(new KeyBinding(exitCommand, new KeyGesture(Key.X, ModifierKeys.Alt));
The RelayCommand class used here is not the part of WPF but it's widely used in MVVM-based apps.
Please note though, that you cannot set your shortcut to X without modifiers. Quote from MSDN
In most cases, a KeyGesture must be associated with one or more ModifierKeys. The exceptions to this rule are the function keys and the numeric keypad keys, which can be a valid KeyGesture by themselves. For example, you can create a KeyGesture by using only the F12 key, but to use the X key in a KeyGesture it must be paired with a modifier key.
If for some reason you need to use X w/o modifiers - you will have to handle keyboard events (eg KeyDown) and react accordingly
回答2:
This works fine for me:
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication5
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
// Create menu item.
MenuItem exitMenuItem = new MenuItem();
exitMenuItem.Header = "E_xit";
exitMenuItem.Click +=new RoutedEventHandler(exitMenuItem_Click);
// Create contextual menu.
ContextMenu contextMenu = new ContextMenu();
contextMenu.Items.Add(exitMenuItem);
// Attach context-menu to something.
myButton.ContextMenu = contextMenu; // Assuming there's a button on window named "myButton".
}
public void exitMenuItem_Click(object sender, RoutedEventArgs e)
{
// This gets executed when user right-clicks button, and presses x down on their keyboard.
// TODO: Exit logic.
}
}
}
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow">
<Grid>
<Button x:Name="myButton" />
</Grid>
</Window>
The exitMenuItem_Click handler gets executed when the user right-clicks the button and presses 'x' on their keyboard. Are you not seeing this happen?
来源:https://stackoverflow.com/questions/10981936/how-do-you-add-access-keys-shortcuts-to-a-wpf-contextmenu-programmatically