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 t开发者_Go百科he 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)));
I found the answer:
InputBindings.Add(new KeyBinding(ChangeToRepositoryCommand, new KeyGesture(Key.F1)) { CommandParameter = 0 });
I apologize if my question was unclear.
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)
精彩评论