如何使用WPF中的Alt键切换主菜单可见性?

ser*_*ist 8 wpf visibility keyboard-shortcuts menu toggle

我希望我的WPF应用程序中的主菜单的行为类似于IE8中的主菜单:

  • 应用程序启动时它不可见
  • 按下并释放Alt使其可见
  • 再次按下并释放Alt使其再次不可见
  • 重复直到无聊

我怎样才能做到这一点?它必须是代码吗?

添加以回应提交的答案,因为我仍然遇到麻烦:

我的Shell代码隐藏现在看起来像这样:

public partial class Shell : Window
{
    public static readonly DependencyProperty IsMainMenuVisibleProperty;

    static Shell()
    {
        FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata();
        metadata.DefaultValue = false;

        IsMainMenuVisibleProperty = DependencyProperty.Register(
            "IsMainMenuVisible", typeof(bool), typeof(Shell), metadata);
    }

    public Shell()
    {
        InitializeComponent();

        this.PreviewKeyUp += new KeyEventHandler(Shell_PreviewKeyUp);
    }

    void Shell_PreviewKeyUp(object sender, KeyEventArgs e)
    {
        if (e.SystemKey == Key.LeftAlt || e.SystemKey == Key.RightAlt)
        {
            if (IsMainMenuVisible == true)
                IsMainMenuVisible = false;
            else
                IsMainMenuVisible = true;
        }
    }

    public bool IsMainMenuVisible
    {
        get { return (bool)GetValue(IsMainMenuVisibleProperty); }
        set { SetValue(IsMainMenuVisibleProperty, value); }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ian*_*kes 8

您可以PreviewKeyDown在窗口上使用该事件.为了检测Alt键,您将需要检查SystemKey的财产KeyEventArgs,而不是您通常使用的大多数其他键的键属性.

您可以使用此事件来设置boolDependencyProperty在后面的Windows代码中声明为a 的值.

Visibility然后可以使用菜单的属性绑定到此属性BooleanToVisibilityConverter.

<Menu 
    Visibility={Binding Path=IsMenuVisibile, 
        RelativeSource={RelativeSource AncestorType=Window},
        Converter={StaticResource BooleanToVisibilityConverter}}
    />
Run Code Online (Sandbox Code Playgroud)