我使用类似于RelayCommand的ICommand类及其类似的变体,但具有扩展属性,这些属性倾向于使用命令。除了将这些属性设置为命令设置的一部分之外,我还可以在绑定时使用它们。例如
<UserControl.InputBindings>
<KeyBinding Command="{Binding SaveCommand}" Key="{Binding SaveCommand.GestureKey}" Modifiers="{Binding SaveCommand.GestureModifier}" />
</UserControl.InputBindings>
现在我想做的是有一种风格来利用这个,类似下面的代码。但它不起作用,因为显然KeyBinding没有DataContext。有没有我可以使这个绑定或类似的东西工作?
干杯,
Berryl
<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”属性上设置“绑定”。 '绑定'只能在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
};
}
}
答案 0 :(得分:1)
在WPF中,您可以创建一个markup extension来为您完成所有分配,或者使用自定义命令类型的新属性将KeyBinding子类化,该属性应该挂接属性更改回调,然后再次设置其他财产。想不出比现在更优雅的东西。