我不知道为什么我的Silverlight4应用程序中的某些对象没有发生数据绑定。以下是我的XAML的大致情况:
<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);
}
我知道这个附加属性工作正常,因为事件处理程序正在触发。然而,
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
. 那为什么我没有
命令
获取数据绑定的属性?另外,您是否找到了调试Silverlight中数据绑定问题的有效方法?
编辑:
至少有一件事是错的
快捷键
来源于
DependencyObject
而不是
FrameworkElement
,这显然是绑定可以应用到的唯一根类。然而,即使在这种变化之后,绑定仍然不能正常工作。