【发布时间】:2023-03-31 09:25:01
【问题描述】:
我使用了一个类似于 RelayCommand 的 ICommand 类及其类似的变体,但具有倾向于与命令一起使用的扩展属性。除了将这些属性设置为命令设置的一部分之外,我还可以在绑定时使用它们。例如
<UserControl.InputBindings>
<KeyBinding Command="{Binding SaveCommand}" Key="{Binding SaveCommand.GestureKey}" Modifiers="{Binding SaveCommand.GestureModifier}" />
</UserControl.InputBindings>
现在我想做的是有一种风格来利用这一点,就像下面的代码一样。但它不起作用,因为显然 KeyBinding 没有 DataContext。有什么办法可以使这个绑定或类似的东西起作用吗?
干杯,
浆果
<Style x:Key="KeyBindingStyle" TargetType="{x:Type KeyBinding}">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="Gesture" Value="{Binding GestureKey}" />
<Setter Property="Modifiers" Value="{Binding GestureModifier}" />
</Style>
<UserControl.InputBindings>
<KeyBinding DataContext="{Binding SaveCommand}" />
</UserControl.InputBindings>
更新
下面是沿 H.B. 扩展 KeyBinding 的第一步。建议,以及我扩展的 Command 类的基本结构。绑定无法编译并出现此错误:无法在“KeyBindingEx”类型的“CommandReference”属性上设置“Binding”。 “绑定”只能在 DependencyObject 的 DependencyProperty 上设置。
<UserControl.InputBindings>
<cmdRef:KeyBindingEx CommandReference="{Binding SaveCommand}"/>
</UserControl.InputBindings>
public class KeyBindingEx : KeyBinding
{
public static readonly DependencyProperty CommandReferenceProperty = DependencyProperty
.Register("VmCommand", typeof(CommandReference), typeof(KeyBindingEx),
new PropertyMetadata(new PropertyChangedCallback(OnCommandReferenceChanged)));
private static void OnCommandReferenceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var kb = (KeyBinding) d;
var cmdRef = (VmCommand)e.NewValue;
kb.Key = cmdRef.GestureKey;
kb.Modifiers = cmdRef.GestureModifier;
kb.Command = cmdRef;
}
public CommandReference CommandReference
{
get { return (CommandReference)GetValue(CommandReferenceProperty); }
set { SetValue(CommandReferenceProperty, value); }
}
}
public class CommandReference : PropertyChangedBase, ICommandReference
{
public Key GestureKey
{
get { return _gestureKey; }
set
{
if (_gestureKey == value) return;
_gestureKey = value;
NotifyOfPropertyChange(() => GestureKey);
}
}
private Key _gestureKey;
...
}
public class VmCommand : CommandReference, ICommand
{
...
public KeyBinding ToKeyBinding()
{
return new KeyBinding
{
Command = this,
Key = GestureKey,
Modifiers = GestureModifier
};
}
}
【问题讨论】:
-
您想要符合 Silverlight 限制的东西,对吧? (编辑:那些 Setter.Value 绑定似乎暗示其他...)
标签: wpf silverlight data-binding key-bindings