views:

61

answers:

2

I am making a custom control I need to add some default keybindings, microsoft has already done with copy and paste in a textbox. However one of the keybindings needs to pass a parameter to the command which it is bound to. It is simple to do this in xaml, is there any way to do this in code?

this.InputBindings.Add(new KeyBinding(ChangeToRepositoryCommand, new KeyGesture(Key.F1)));
+1  A: 

The copy and paste commands are handled by the text box so parameters are not strictly passed, but i know what you are getting at.

I do this using a hack - and an attached property, like so

   public class AttachableParameter : DependencyObject {

      public static Object GetParameter(DependencyObject obj) {
         return (Object)obj.GetValue(ParameterProperty);
      }

      public static void SetParameter(DependencyObject obj, Object value) {
         obj.SetValue(ParameterProperty, value);
      }

      // Using a DependencyProperty as the backing store for Parameter.  This enables animation, styling, binding, etc...
      public static readonly DependencyProperty ParameterProperty =
          DependencyProperty.RegisterAttached("Parameter", typeof(Object), typeof(AttachableParameter), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));
}

then in the xaml

<ListBox local:AttachableParameter.Parameter="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItems}" />

which makes the parameter the selected items

then when the command fires on the window i use this to see if the command parameter is there (i call this from the can execute and the Executed)

  private Object GetCommandParameter() {
     Object parameter = null;
     UIElement element = FocusManager.GetFocusedElement(this) as UIElement;
     if (element != null) {
        parameter = AttachableParameter.GetParameter(element as DependencyObject);
     }
     return parameter;
  }

It is a hack, but i have not found another way to get the command parameter for a binding that is fired from a key binding. (I would love to know a better way)

Aran Mulholland
It's so easy to do what I need in xaml with:<KeyBinding Command="{Binding ChangeRepositoryCommand}" Gesture="Ctrl+1" CommandParameter="0"/>I wonder why they don't let you do it in code.
Justin
A: 

I found the answer:

InputBindings.Add(new KeyBinding(ChangeToRepositoryCommand, new KeyGesture(Key.F1)) { CommandParameter = 0 });

I apologize if my question was unclear.

Justin
Your solution is much more readable this way: `InputBindings.Add(new KeyBinding(ChangeToRepositoryCommand, new KeyGesture(Key.F1)) { CommandParameter = 0 });`
Ray Burns
Thank you. Updated.
Justin