我想将自定义类型(BoundItem)的ObservableCollection绑定到视图.
我这样使用它:
<v:MyUserControlBase x:Class="My.Views.MyView"
(...)
h:FrameworkElementDropBehavior.MyItems="{Binding Attachments}">
附件在ViewModel中定义为:
public ObservableCollection<BoundItem> Attachments
{
get { return _Attachments; }
set { _Attachments = value; }
}
我的视图是一个实际的DependencyObject,因为当我在视图后面的代码中执行以下代码时:
MessageBox.Show((this as DependencyObject).ToString());
它显示“真实”.
我这样定义了我的Dependency Property:
public static readonly DependencyProperty MyItemsProperty = DependencyProperty.RegisterAttached("MyItems", typeof(ObservableCollection<BoundItem>), typeof(MyView), new FrameworkPropertyMetadata(null));
public static string GetMyItems(DependencyObject element)
{
if (element == null) throw new ArgumentNullException("MyItems");
return (ObservableCollection<BoundItem>)element.GetValue(MyItemsProperty);
}
public static void SetMyItems(DependencyObject element, ObservableCollection<BoundItem> value)
{
if (element == null) throw new ArgumentNullException("MyItems");
element.SetValue(MyItemsProperty, value);
}
发生的错误是:
A ‘Binding’ cannot be set on the ‘SetMyItems’ property of type ‘MyView’. A ‘Binding’ can only be set on a DependencyProperty of a DependencyObject.
谢谢你的帮助:) .x
最佳答案 问题在于您的财产注册.而不是所有者类型MyView它应该是FrameworkElementDropBehavior i,即您定义属性的类.
public static readonly DependencyProperty MyItemsProperty =
DependencyProperty.RegisterAttached("MyItems",
typeof(ObservableCollection<BoundItem>),
typeof(FrameworkElementDropBehavior),
new FrameworkPropertyMetadata(null));