我希望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); }
        }
    }
    

    最佳答案

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

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

    然后可以使用Visibility将菜单的BooleanToVisibilityConverter属性绑定(bind)到此属性。

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

    10-05 20:33
    查看更多