我需要为每个控件 + 数字组合创建热键,并且不希望创建十个命令。有没有办法做到这一点?
问问题
7584 次
2 回答
12
如果我理解你的问题,你有一个命令,比如说MyCommand
,如果用户按下 CTRL+0 到 CTRL+9,你想触发它,并为每个组合给命令一个不同的参数。
在这种情况下,只需在您的窗口中创建 10 个键绑定,全部绑定到MyCommand
,并给它们一个参数:
<Window.InputBindings>
<KeyBinding Command="MyCommand" Gesture="Ctrl+0" CommandParameter="0"/>
<KeyBinding Command="MyCommand" Gesture="Ctrl+1" CommandParameter="1"/>
<KeyBinding Command="MyCommand" Gesture="Ctrl+2" CommandParameter="2"/>
<KeyBinding Command="MyCommand" Gesture="Ctrl+3" CommandParameter="3"/>
<KeyBinding Command="MyCommand" Gesture="Ctrl+4" CommandParameter="4"/>
<KeyBinding Command="MyCommand" Gesture="Ctrl+5" CommandParameter="5"/>
<KeyBinding Command="MyCommand" Gesture="Ctrl+6" CommandParameter="6"/>
<KeyBinding Command="MyCommand" Gesture="Ctrl+7" CommandParameter="7"/>
<KeyBinding Command="MyCommand" Gesture="Ctrl+8" CommandParameter="8"/>
<KeyBinding Command="MyCommand" Gesture="Ctrl+9" CommandParameter="9"/>
</Window.InputBindings>
于 2010-03-13T05:41:38.130 回答
6
是的,您可以创建一个自定义 KeyBinding 来执行此操作。代码看起来像这样:
[ContentProperty("Keys")]
public class MultiKeyBinding : InputBinding
{
public ModifierKeys Modifiers;
public List<Key> Keys = new List<Key>();
private Gesture _gesture;
public override InputGesture Gesture
{
get
{
if(_gesture==null) _gesture = new MultiKeyGesture { Parent = this };
return _gesture;
}
set { throw new InvalidOperationException(); }
}
class MultiKeyGesture : InputGesture
{
MultiKeyBinding Parent;
public override bool Matches(object target, InputEventArgs e)
{
bool match =
e is KeyEventArgs &&
Parent.Modifiers == Keyboard.Modifiers &&
Parent.Keys.Contains( ((KeyEventArgs)e).Key );
// Pass actual key as CommandParameter
if(match) Parent.CommandParameter = ((KeyEventArgs)e).Key;
return match;
}
}
}
它将像这样使用:
<local:MultiKeyBinding Command="..." Modifiers="Control">
<Key>D0</Key>
<Key>D1</Key>
...
</local:MultiKeyBinding>
希望这可以帮助。
于 2010-03-13T05:46:24.043 回答