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

问题描述 投票:8回答:5

我想让我的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); }
    }
}
wpf menu keyboard-shortcuts toggle visibility
5个回答
8
投票

你可以使用 PreviewKeyDown 窗口上的事件。要检测 祭祀 钥匙,你将需要检查 SystemKey 的财产 KeyEventArgs而不是通常用于大多数其他键的 Key 属性。

您可以使用这个事件来设置一个 bool 值,该值已被声明为 DependencyProperty 在后面的windows代码中。

菜单的 Visibility 属性,然后可以使用 BooleanToVisibilityConverter.

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

2
投票

我自己也遇到了这个问题。我试着连接到 PreviewKeyDown 事件,但发现它不可靠。相反,我发现 InputManager 类,在那里你可以钩入 EnterMenuMode 从管理的代码。管理器暴露了两个事件,用于进入和退出。诀窍是不要折叠菜单,但当它要被隐藏时,要将它的容器高度设置为零。要显示它,只需清除本地的值,它就会以之前的高度显示。

从我的 TopMenu 用户控制。

public TopMenu()
{
    InitializeComponent();
    InputManager.Current.EnterMenuMode += OnEnterMenuMode;
    InputManager.Current.LeaveMenuMode += OnLeaveMenuMode;
    Height = 0;
}

private void OnLeaveMenuMode(object sender, System.EventArgs e)
{
    Height = 0;
}

private void OnEnterMenuMode(object sender, System.EventArgs e)
{
    ClearValue(HeightProperty);
}

1
投票

我想看看如何处理 PreviewKeyDown 事件。我不确定按Alt键是否会触发这个事件,但如果会的话,我就会在窗口上切换一个 bool 这与窗口的主菜单的可见性有关。

如果 PreviewKeyDown 不起作用,我不知道还能试什么。你可以查看发送到你的窗口的实际Windows消息,但那可能很快就会变得混乱。


1
投票

最好是使用 GetKeyboardStateVK_MENU 左右都能处理 祭祀为了模仿IE Windows Explorer (Vista+)的行为,你需要跟踪之前的焦点元素,以存储焦点,在一个 VK_MENU 当焦点元素在你的主菜单中时,按下。你也希望在 PreviewKeyUp (不是向下)。


0
投票

请看我对下面帖子的回答。如何使WPF MenuBar在ALT键被按下时可见?

在那里我描述了如何用类来解决你的问题。InputManager (来自命名空间 System.Windows.Input).

你可以注册班级活动 EnterMenuModeLeaveMenuMode.

© www.soinside.com 2019 - 2025. All rights reserved.