As indicated in other answers, setting IsAltKeyRequiredInAccessKeyDefaultScope
avoids invoking actions for access keys without pressing the Alt key. However, this can also disable the Enter key (to invoke the default action) and the Esc key (to invoke the Cancel action).
Using the proposed workaround instead, and testing for Key.Enter
and Key.Escape
, can work around this problem. However, you may find that menu items cannot be selected by the access key without pressing the Alt key, which can be a problem if the button in the area uses the same access key.
An alternative would be to access the access key event, checking if the potentially called AccessText
control is within the MenuItem
or not, something like these lines:
EventManager.RegisterClassHandler( typeof(UIElement), AccessKeyManager.AccessKeyPressedEvent, new AccessKeyPressedEventHandler(OnAccessKeyPressed));
...
static void OnAccessKeyPressed(object accessKeyTarget, AccessKeyPressedEventArgs e) { if (!e.Handled && e.Scope == null && (Keyboard.Modifiers & ModifierKeys.Alt) != ModifierKeys.Alt && !ShouldElementHandleAccessKeysWhenAltIsNotPressed(accessKeyTarget as UIElement)) { e.Target = null; e.Handled = true; } } static bool ShouldElementHandleAccessKeysWhenAltIsNotPressed(UIElement element) { if (element == null) return false; var accessText = element as AccessText; if (accessText != null && !IsDecendantOfMenuItem(accessText)) return false; return true; } static bool IsDecendantOfMenuItem(DependencyObject element) { for (; element != null; element = VisualTreeHelper.GetParent(element)) if (element is MenuItem) return true; return false; }
source share