WPF中的LeftAlt键绑定 [英] LeftAlt Keybinding in WPF
问题描述
我正在尝试将左ALT键与命令绑定在一起,以切换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>
我注意到其他特殊键(例如Alt,Ctrl等)在这里也不起作用.
I've noticed that other special Keys ( such as Alt, Ctrl etc..) also not working here..
如何在WPF中对特殊键进行键绑定?
How to do KeyBinding for Special Key in WPF ?
推荐答案
这些特殊的键称为修饰符"键,这应该弄清楚为什么它不起作用.修饰键用于修改"给定键的行为,例如Shift + L表示大写字母"L",而只有L表示小写字母"l".使用Modifierkeys进行实际逻辑操作可能会引起麻烦和烦躁,因为用户不习惯于按这些按钮时看到正在发生的实际动作.但是我同意在某些地方这是有意义的,例如按下ALT键时突出显示MenuItems.
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.
但是对于您的实际问题:您可以使用codebehind和OnKeyDown/OnKeyUp或Preview事件来实现此行为.
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);
}
当然,cou也可以在此代码中触发您的命令.
Of course cou could also fire your command in this code.
这篇关于WPF中的LeftAlt键绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!