Won*_*ane 15 wpf binding .net-4.0 itemtemplate itemscontrol
在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; }
}
Run Code Online (Sandbox Code Playgroud)
在我的窗口中,我有一个带有以下内容的ItemsControl(为了清晰起见而剪裁):
<ItemsControl ItemsSource={Binding}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:MyDisplayControl
OwnerName={Binding OwnerData.OwnerName}
Credit={Binding Credit} />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
然后我得到的数据层显示信息的集合,并设置DataContext的ItemsControl这个集合."Credit"属性正确显示,但OwnerName属性不正确.相反,我得到一个绑定错误:
错误40:BindingExpression路径错误:'对象'上找不到'OwnerName'属性''ForDisplay'(HashCode = 449124874)'.BindingExpression:路径= OWNERNAME; DataItem ='ForDisplay'(HashCode = 449124874); target元素是'TextBlock'(Name = txtOwnerName'); target属性是'Text'(类型'String')
我不明白为什么这会尝试在ForDisplay类中查找OwnerName属性,而不是在ForDisplay OwnerData属性的Owner类中查找.
编辑
它似乎与使用自定义控件有关.如果我将相同的属性绑定到a 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>
Run Code Online (Sandbox Code Playgroud)
您确定您在此处发布的代码是您在解决方案中使用的代码吗?因为,这段代码对我有用:
XAML
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding OwnerData.OwnerName}"></TextBlock>
<TextBlock Text="{Binding Credit}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
Window的加载事件
ObservableCollection<ForDisplay> items = new ObservableCollection<ForDisplay>();
for (int i = 0; i < 10; i++)
{
items.Add(new ForDisplay() { OwnerData = new Owner() { OwnerId = i + 1, OwnerName = String.Format("Owner #{0}", i + 1) }, Credit = i + 1 });
}
DataContext = items;
Run Code Online (Sandbox Code Playgroud)