简体   繁体   English

无法将Observable Collection绑定到UserControl上的Attached属性

[英]Cannot bind an Observable Collection to an Attached Property on an UserControl

I want to bind an ObservableCollection of custom type (BoundItem) to a view. 我想将自定义类型(BoundItem)的ObservableCollection绑定到视图。

I am using it this way : 我这样使用它:

<v:MyUserControlBase x:Class="My.Views.MyView"
         (...)
         h:FrameworkElementDropBehavior.MyItems="{Binding Attachments}">

Attachments is defined in the ViewModel as : 附件在ViewModel中定义为:

public ObservableCollection<BoundItem> Attachments 
{ 
   get { return _Attachments; } 
   set { _Attachments = value; } 
}

My view is an actual DependencyObject since when I do in the code behind of the view the following piece of code: 我的视图是一个实际的DependencyObject,因为当我在视图后面的代码中执行以下代码时:

MessageBox.Show((this as DependencyObject).ToString());

it shows "True". 它显示“真实”。

I defined my Dependency Property that way: 我这样定义了我的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);
    }

The error that occurs is: 发生的错误是:

A 'Binding' cannot be set on the 'SetMyItems' property of type 'MyView'. 无法在“MyView”类型的“SetMyItems”属性上设置“绑定”。 A 'Binding' can only be set on a DependencyProperty of a DependencyObject. '绑定'只能在DependencyObject的DependencyProperty上设置。

Thanks for you help :) .x 谢谢你的帮助:) .x

Problem is with your property registration. 问题在于您的财产注册。 Instead of owner type MyView it should be FrameworkElementDropBehavior i,e the class where you are defining your property. 而不是所有者类型MyView它应该是FrameworkElementDropBehavior i,即您定义属性的类。

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

此外,SetMyItems第二个参数应为ObservableCollection类型,GetMyItems应具有返回类型ObservableCollection。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM