【问题标题】:Cannot bind an Observable Collection to an Attached Property on an UserControl无法将 Observable 集合绑定到 UserControl 上的附加属性
【发布时间】:2015-06-26 21:38:07
【问题描述】:

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

它显示“真”。

我以这种方式定义了我的依赖属性:

    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

【问题讨论】:

    标签: c# wpf xaml binding dependency-properties


    【解决方案1】:

    问题在于您的财产登记。而不是所有者类型MyView,它应该是FrameworkElementDropBehavior,即您定义属性的类。

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

    【讨论】:

      【解决方案2】:

      另外,SetMyItems 的第二个参数应该是 ObservableCollection 类型,GetMyItems 应该有返回类型 ObservableCollection。

      【讨论】:

      • 糟糕,已修复,但错误仍然存​​在。谢谢(:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 2018-01-30
      • 2011-12-26
      • 2012-12-31
      • 1970-01-01
      相关资源
      最近更新 更多