我正在制作一个自定义控件,我需要添加一些默认的键绑定,微软已经在文本框中完成了复制和粘贴。但是,其中一个键绑定需要将参数传递给它所绑定的命令。在 xaml 中执行此操作很简单,有没有办法在代码中执行此操作?
this.InputBindings.Add(new KeyBinding(ChangeToRepositoryCommand, new KeyGesture(Key.F1)));
我正在制作一个自定义控件,我需要添加一些默认的键绑定,微软已经在文本框中完成了复制和粘贴。但是,其中一个键绑定需要将参数传递给它所绑定的命令。在 xaml 中执行此操作很简单,有没有办法在代码中执行此操作?
this.InputBindings.Add(new KeyBinding(ChangeToRepositoryCommand, new KeyGesture(Key.F1)));
我找到了答案:
InputBindings.Add(new KeyBinding(ChangeToRepositoryCommand, new KeyGesture(Key.F1)) { CommandParameter = 0 });
如果我的问题不清楚,我深表歉意。
复制和粘贴命令由文本框处理,因此参数没有严格传递,但我知道你在做什么。
我使用 hack 和附加属性来做到这一点,就像这样
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;
}
这是一个 hack,但我还没有找到另一种方法来获取从键绑定触发的绑定的命令参数。(我很想知道更好的方法)