【问题标题】:Binding to observable collection, dependency property fails绑定到可观察集合,依赖属性失败
【发布时间】:2013-01-19 21:30:10
【问题描述】:

我有一个用户控件,我需要一个我创建的简单类的列表,称为 Person:

public class Person {
    public string Name { get; set; }
}

现在在用户控件中,我需要一个可以绑定的 ObservableCollection。所以我想我需要让它成为一个依赖属性。所以在用户控件中我有以下内容:

public static readonly DependencyProperty PersonsDependencyProperty =
    DependencyProperty.Register("Persons", typeof(ObservableCollection<Person>),
                                typeof(PersonUserControl));

而属性是这样的:

public ObservableCollection<Person> Persons
{
   get
    {
        return (ObservableCollection<Person>)GetValue(PersonsDependencyProperty);
    }
    set
    {
        SetValue(PersonsDependencyProperty, value);
    }
}

现在在我的 MainWindow.xaml 代码隐藏中,我创建了一个名为 PersonList 的 ObservableCollection,将主窗口数据上下文设置为 self,然后像这样绑定到它:

<Local:PersonUserControl Persons="{Binding PersonList}">
</Local:PersonUserControl>

我得到了错误:调用的目标抛出了异常。 - 没有进一步的解释。谁能告诉我如何应对它或我做错了什么。

我希望我说得够清楚了。

【问题讨论】:

  • 您能否发布堆栈跟踪以及内部异常(如果有)?顺便说一句,您应该将您的财产命名为PersonsProperty,所以它应该是public static readonly DependencyProperty PersonsDependencyProperty
  • 能否请您出示您的 xaml.cs 文件代码

标签: wpf binding user-controls dependency-properties invocationtargetexception


【解决方案1】:

PersonsDependencyProperty 应该只是 PersonsProperty。如果没有更多信息,很难说这是否是根本原因,但这肯定是一个问题。 WPF 将“属性”附加到绑定路径以查找相关的依赖项属性。因此,它不会找到您的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 2021-11-22
    • 2020-06-05
    相关资源
    最近更新 更多