我正在尝试从DataTemplate绑定到父数据上下文。当我这样做的时候
ItemsSource="{Binding DataContext.(viewModels:UmowaViewModel.ZrodlaOprocentowania),
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
它失败,“WindowsBase.dll中发生了'System.ArgumentNullException'类型的未处理异常。附加信息:Key不能为空”
但是当我省略上下文类型它有效但我在VS中强调了属性无法解析 - 为什么它在指定数据类型后中断?
ItemsSource="{Binding DataContext.(viewModels:UmowaViewModel.ZrodlaOprocentowania),
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
答案 0 :(得分:1)
我不确定你有什么想法随机地将命名空间和Type
注入Binding.Path
,但我很确定它是无效的......至少,我我从来没有碰到任何Binding.Path
这样的人:
ItemsSource="{Binding DataContext.(viewModels:UmowaViewModel.ZrodlaOprocentowania),
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
括号往往在Binding Path
中用于表示附加属性,但DataContext
属性不是附加属性。除此之外,您应该使用仅引用属性名称的普通Binding Path
和RelativeSource
,如下所示:
ItemsSource="{Binding DataContext,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
现在这是明确和正确的......我们正在尝试将数据绑定到父DataContext
对象的UserControl
属性。所以回答你的问题为什么第二个例子工作但不是第一个?,我会说,因为第二个例子是有效的,但第一个例子不是。您可以在MSDN上看到Property Path Syntax页面,以获取有效Binding Path
语法的更多帮助。