创建一个键绑定,每次使用任何数字按下控件时都会触发命令,然后将该数字作为参数传递?

Jus*_*tin 8 c# wpf xaml command key-bindings

我需要为每个控件+数字组合创建热键,并且不希望创建十个命令.有没有办法做到这一点?

Ben*_*gan 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>
Run Code Online (Sandbox Code Playgroud)


Ray*_*rns 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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

它会像这样使用:

<local:MultiKeyBinding Command="..." Modifiers="Control">
  <Key>D0</Key>
  <Key>D1</Key>
  ...
</local:MultiKeyBinding>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.