繁体   English   中英

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

[英]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());

它显示“真实”。

我这样定义了我的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);
    }

发生的错误是:

无法在“MyView”类型的“SetMyItems”属性上设置“绑定”。 '绑定'只能在DependencyObject的DependencyProperty上设置。

谢谢你的帮助:) .x

问题在于您的财产注册。 而不是所有者类型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