Is there a way to pass a parameter to a command through a key binding performed in code?

I am creating a custom control, I need to add some keywords by default, microsoft has already completed the copy and paste operation in the text box. However, one of the keys needs to pass the parameter to the command to which it is attached. This is easy to do in xaml, is there any way to do this in code?

this.InputBindings.Add(new KeyBinding(ChangeToRepositoryCommand, new KeyGesture(Key.F1)));
+3
source share
2 answers

I found the answer:

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

Sorry if my question is unclear.

+4
source

Copy and paste commands are processed by a text field, so the parameters are not strictly passed, but I know what you get.

- ,

   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));
}

xaml

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

, , , , ( )

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

, , . ( )

+1

Source: https://habr.com/ru/post/1741020/


All Articles