无法将 Observable 集合绑定到 UserControl 上的附加 属性

Cannot bind an Observable Collection to an Attached Property on an UserControl

我想将自定义类型 (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());

它显示 "True"。

我这样定义我的依赖关系 属性:

    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 即 class 你定义你的 属性.

public static readonly DependencyProperty MyItemsProperty =
     DependencyProperty.RegisterAttached("MyItems", 
                                        typeof(ObservableCollection<BoundItem>), 
                                        typeof(FrameworkElementDropBehavior), 
                                        new FrameworkPropertyMetadata(null));

此外,SetMyItems 的第二个参数应该是 ObservableCollection 类型,而 GetMyItems 应该是 return 类型的 ObservableCollection。