如何使用WPF中的Alt键切换主菜单的可见性? [英] How can I toggle the main menu visibility using the Alt key in WPF?

查看:164
本文介绍了如何使用WPF中的Alt键切换主菜单的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like the main menu in my WPF app to behave like the main menu in IE8:

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

我该怎么做?一定是代码吗?

How can I do this? Does it have to be code?

添加了对我提交的答案的答复,因为我仍然遇到问题:

我的Shell背后的代码现在看起来像这样:

My Shell code-behind now looks like this:

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); }
    }
}

推荐答案

您可以在窗口上使用PreviewKeyDown事件.要检测 Alt 键,您需要检查KeyEventArgsSystemKey属性,而不是通常用于大多数其他键的Key属性.

You can use the PreviewKeyDown event on the window. To detect the Alt key you will need to check the SystemKey property of the KeyEventArgs, as opposed to the Key property which you normally use for most other keys.

您可以使用此事件来设置bool值,该值已在后面的Windows代码中声明为DependencyProperty.

You can use this event to set a bool value which has been declared as a DependencyProperty in the windows code behind.

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

The menu's Visibility property can then be bound to this property using the BooleanToVisibilityConverter.

<Menu 
    Visibility={Binding Path=IsMenuVisibile, 
        RelativeSource={RelativeSource AncestorType=Window},
        Converter={StaticResource BooleanToVisibilityConverter}}
    />

这篇关于如何使用WPF中的Alt键切换主菜单的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆