Wpf – How to toggle the main menu visibility using the Alt key in WPF

keyboard shortcutsmenutogglevisibilitywpf

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

  • it's not visible when the app starts
  • pressing and releasing Alt makes it visible
  • pressing and releasing Alt again makes it invisible again
  • repeat until bored

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

Added in response to answers submitted, because I'm still having trouble:

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

Best Answer

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.

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

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}}
    />
Related Topic