绑定到可观察集合,依赖属性失败

时间:2013-01-19 21:30:11

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

我有一个usercontrol,我需要一个我做过的简单类的列表,名为Person:

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

现在在usercontrol中,我需要一个ObservableCollection< Person>我可以绑定。所以我认为我需要使它成为依赖属性。所以在usercontrol中我有以下内容:

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代码隐藏中,我创建了一个ObservableCollection&lt; Person&gt;调用PersonList,将mainwindow datacontext设置为self,并像这样绑定到它:

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

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

我希望我足够清楚。

1 个答案:

答案 0 :(得分:0)

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

相关问题