Search code examples
c#wpfmvvmkey-bindings

LeftAlt Keybinding in WPF


I'm trying to bind Left ALT key with a command to toggle visibility of a menu in WPF. But it doesn't work.. Command is not firing..

<Window.InputBindings>
        <KeyBinding
            Key="LeftAlt"
            Command="{Binding Path=MenuVisibilitySetCommand}"/>
</Window.InputBindings>

I've noticed that other special Keys ( such as Alt, Ctrl etc..) also not working here..

How to do KeyBinding for Special Key in WPF ?


Solution

  • These special Keys are called Modifier keys and this should make it clear why it is not working. A modifier Key is to "modify" the behavior of a given key, Like Shift + L makes an uppercase "L" where only the L key makes a lowercase "l". Using Modifierkeys for actual logic can be problematic and irritating, because the user is not accustomed to see real actions happening when pressing these kind of buttons. But i agree there are places where this makes sense e.g. highlighting MenuItems when hitting ALT key.

    But to your actual problem: You could use codebehind and the OnKeyDown/OnKeyUp or the Preview events to implement this behavior.

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if(e.SystemKey == Key.LeftAlt)
            {
                myMenu.Visibility = Visibility.Visible;
                // e.Handled = true; You need to evaluate if you really want to mark this key as handled!
            }
    
            base.OnKeyDown(e);
        }
    

    Of course cou could also fire your command in this code.