我不知道爲什麼我的Silverlight 4應用程序中某些對象沒有發生數據綁定。這是我的XAML看起來大約是這樣的:爲什麼Silverlight 4 DependencyObject的DependencyProperty不能獲取數據綁定?
<sdk:DataGrid>
<u:Command.ShortcutKeys>
<u:ShortcutKeyCollection>
<u:ShortcutKey Key="Delete" Command="{Binding Path=MyViewModelProperty}"/>
</u:ShortcutKeyCollection>
</u:Command.ShortcutKeys>
</sdk:DataGrid>
數據上下文設置就好了,因爲我已經在網格設置的其他數據綁定工作得很好。該Command.ShortcutKeys
是,聲明如下附加DependencyProperty
:
public static readonly DependencyProperty ShortcutKeysProperty = DependencyProperty.RegisterAttached(
"ShortcutKeys", typeof(ShortcutKeyCollection),
typeof(Command), new PropertyMetadata(onShortcutKeysChanged));
private static void onShortcutKeysChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var shortcuts = args.NewValue as ShortcutKeyCollection;
if (obj is UIElement && shortcuts != null)
{
var element = obj as UIElement;
shortcuts.ForEach(
sk => element.KeyUp += (s, e) => sk.Command.Execute(null));
}
}
public static ShortcutKeyCollection GetShortcutKeys(
DependencyObject obj)
{
return (ShortcutKeyCollection)obj.GetValue(ShortcutKeysProperty);
}
public static void SetShortcutKeys(
DependencyObject obj, ShortcutKeyCollection keys)
{
obj.SetValue(ShortcutKeysProperty, keys);
}
我知道這個附加屬性是工作得很好,因爲事件處理程序已觸發。但ShortcutKey
對象的Command
屬性未獲取數據綁定。下面是ShortcutKey
定義:
public class ShortcutKey : DependencyObject
{
public static readonly DependencyProperty KeyProperty = DependencyProperty.Register(
"Key", typeof(Key), typeof(ShortcutKey), null);
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
"Command", typeof(ICommand), typeof(ShortcutKey), null);
public Key Key
{
get { return (Key)GetValue(KeyProperty); }
set { SetValue(KeyProperty, value); }
}
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
}
public class ShortcutKeyCollection : ObservableCollection<ShortcutKey> { }
,這是獲得必然有其價值在我看來模型的構造函數中設置的屬性,它的類型是ICommand
。那麼,爲什麼我的Command
屬性不能獲取數據綁定?另外,您是否找到了一種在Silverlight中調試數據綁定問題的有效方法?
編輯:錯了
至少有一點是,從ShortcutKey
代替DependencyObject
的FrameworkElement
衍生,這顯然是該結合可以被施加到僅根類。但是,即使在更改之後,綁定仍然無法正常工作。
您可以加入的如何通過XAML設置了'Binding'源和而無需'StaticResource'爲例?我嘗試了幾種方法來做到這一點,但都沒有成功。 – Jacob 2010-07-20 00:29:26
謝謝你的例子,但我已經試過做幾乎完全一樣。通過該代碼,'DataContext'可以在'ShortcutKey'對象上正確設置,但綁定操作仍然沒有發生。 – Jacob 2010-07-20 00:55:55
是MyViewModelProperty一個DependencyProperty或你viewmodel實現IPropertyChanged? – Ozan 2010-07-20 01:21:26