我使用類似於RelayCommand的ICommand類以及類似的變體,但是擴展屬性傾向於使用命令。除了將這些屬性設置爲Command設置的一部分之外,我還可以在綁定時使用它們。例如KeyBinding樣式
<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>
UPDATE
下面是在沿着切斷預定線延伸的鍵綁定該H.B.第一遍與我擴展的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
};
}
}
你想要的東西與Silverlight的限制兼容,對吧? (編輯:那些Setter.Value綁定似乎表明否則...) – 2011-06-15 23:54:38