【发布时间】:2010-06-17 15:21:35
【问题描述】:
在 WPF4.0 中,我有一个包含其他类类型作为属性的类(组合多种数据类型进行显示)。比如:
public partial class Owner
{
public string OwnerName { get; set; }
public int OwnerId { get; set; }
}
partial class ForDisplay
{
public Owner OwnerData { get; set; }
public int Credit { get; set; }
}
在我的窗口中,我有一个 ItemsControl,其中包含以下内容(为清楚起见已剪辑):
<ItemsControl ItemsSource={Binding}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:MyDisplayControl
OwnerName={Binding OwnerData.OwnerName}
Credit={Binding Credit} />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
然后我从数据层获取显示信息的集合,并将ItemsControl 的DataContext 设置为这个集合。 “Credit”属性正确显示,但 OwnerName 属性没有。相反,我得到一个绑定错误:
错误 40:BindingExpression 路径 错误:找不到“所有者名称”属性 在'对象'''ForDisplay' (哈希码=449124874)'。 绑定表达式:路径=所有者名称; DataItem='ForDisplay' (哈希码=449124874);目标元素 是'文本块'(名称=txtOwnerName'); 目标属性是“文本”(类型 '字符串')
我不明白为什么这是试图在 ForDisplay 类中查找 OwnerName 属性,而不是在 ForDisplay OwnerData 属性的 Owner 类中。
编辑
看来它与使用自定义控件有关。如果我将相同的属性绑定到 TextBlock,它们就可以正常工作。
<ItemsControl ItemsSource={Binding}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<local:MyDisplayControl
OwnerName={Binding OwnerData.OwnerName}
Credit={Binding Credit} />
<TextBlock Text="{Binding OwnerData.OwnerName}" />
<TextBlock Text="{Binding Credit}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
【问题讨论】:
-
不知何故,它试图在 ForDisplay 对象上找到 OwnerName 属性。使用以下链接进行调试:wpftutorial.net/DebugDataBinding.html。还有一个问题,您的 MyDisplayControl 上的 OwnerName 属性是依赖属性吗?
-
我看不出有什么问题,假设您剪辑的内容没有隐藏任何相关内容。您是否尝试过清理/重建解决方案?我讨厌这个建议,因为它相当于告诉你“重新启动”,但是我有一个数据绑定情况,应该可以工作但不能,我发现清理/重建有时会修复它。不知道为什么。
-
一个初步猜测:更改 Binding 以显式设置 Path。即“OwnerName={绑定路径=OwnerData.OwnerName}”
-
我的设计也是这样。但它在
<DataTemplate>抛出 NullReferenceException
标签: wpf binding .net-4.0 itemscontrol itemtemplate