WPF:按下Alt键时,我的ContextMenu将无法打开

时间:2013-03-06 12:02:27

标签: .net wpf contextmenu alt-key

在我的WPF应用中,当ContextMenu正在打开时,我想调整其菜单项,具体取决于是否按下Alt键。

我的逻辑工作正常。 XAML:

<my:Control ContextMenuOpening="MyContextMenu_Opening" />

代码:

private void MyContextMenu_Opening(object sender, RoutedEventArgs args) {
  bool isAltDown = Keyboard.IsKeyDown(Key.LeftAlt);
  /* tweak menu items here */
}

我的问题是,当按下Alt键时,上下文菜单会打开,然后立即关闭(我可以看到它的闪存正在打开,我的逻辑至少正常工作)。

我想知道这是一个WPF'功能',因为如果我在右键单击Alt时按住TextField,同样的事情就会发生 - 内置的剪切/复制/粘贴菜单闪烁然后立即关闭。

一种预感是它与Alt激活应用程序菜单栏有关。但是应用程序菜单栏不适用于我的情况,所以如果解决方案涉及到它,它仍然适用于我。

3 个答案:

答案 0 :(得分:3)

这是MenuBase类中的内置行为:

        protected override void OnKeyDown(KeyEventArgs e)
        {
            .....
            if (((e.SystemKey == Key.LeftAlt) || (e.SystemKey == Key.RightAlt)) || (e.SystemKey == Key.F10))
            {
                this.KeyboardLeaveMenuMode();
                e.Handled = true;
            }
        }

为什么不使用其他修饰键?

答案 1 :(得分:1)

这是一种内置行为 来自MSDN MenuBase.OnKeyDown

    If the user presses ESC, ALT+ALT, or ALT+F10, 
    this implementation marks the KeyDown event as handled 
    by setting the Handled property of the event data to true.

答案 2 :(得分:0)

您仍然可以使用Alt键,只是覆盖基类的行为:

public class AltProofContextMenu : ContextMenu
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if(!(e.SystemKey == Key.LeftAlt || e.SystemKey == Key.RightAlt))
            base.OnKeyDown(e);
    }
}
相关问题