LeftAlt Keybinding in WPF

2019-08-06 09:05发布

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 ?

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-06 09:29

For LeftALt to work like this, you also need to set Modifiers property to Alt.

<KeyBinding Key="LeftAlt" Modifiers="Alt" Command="{Binding Path=MenuVisibilitySetCommand}"/>
查看更多
何必那么认真
3楼-- · 2019-08-06 09:39

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.

查看更多
登录 后发表回答