我不知道为什么我的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