问题描述
作为我关于SO的第一个TreeView问题的后续,我无法将 TreeView 控件绑定到我的 Commission 对象的 Id 属性及其在同一个 TreeView 控件中的 Products 集合.这是我的简化模型:
As a follow up to my first TreeView question on SO, I'm unable to bind a TreeView control to the Id property of my Commission object and its Products collection in the same TreeView control.Here's my simplified model:
internal class Contract
{
public string Name { get; set; }
public ObservableCollection<Commission> Commissions { get; set; }
}
internal class Commission
{
public string Id { get; set; }
public ObservableCollection<Product> Products { get; set; }
}
internal class Product
{
public string Code { get; set; }
}
这是我的问题 XAML.合约返回佣金对象(Commissions)的集合.我已经注释掉了用于返回产品的 HierarchicalDataTemplate.任一 HierarchicalDataTemplate 都可以单独工作,但如果两者都未注释则不行:
Here's my problem XAML. Contract returns a collection of Commission objects (Commissions). I've commented out the HierarchicalDataTemplate for returning Products. Either HierarchicalDataTemplate will work individually, but not if both are uncommented:
<TreeView ItemsSource="{Binding Contract.Commissions}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type m:Commission}">
<TextBlock Text="{Binding Id}" />
</HierarchicalDataTemplate>
<!--<HierarchicalDataTemplate DataType="{x:Type m:Commission}" ItemsSource="{Binding Products}">
<TextBlock Text="{Binding Code}" />
</HierarchicalDataTemplate>-->
</TreeView.Resources>
</TreeView>
如果两个 HierarchicalDataTemplates 都未注释,则会抛出错误,因为我使用了两次唯一的(Commission Type),但我不知道如何在不使用 Commission Type 作为模板的 DataType 的情况下使 HierarchicalDataTemplate 工作.
If both HierarchicalDataTemplates are uncommented, an error is thrown because I'm using a unique (Commission Type) twice, but I don't know how to make either HierarchicalDataTemplate work without using Commission Type as the template's DataType.
推荐答案
你在这里搞混了.我假设您想显示 Commission 的 Id 以及在每个 Commission 节点下方,子产品的代码值.
You are jumbling up things here. I assume you want to show Commission's Id and beneath each Commission node, child Product's code value.
只需要一个HierarchicalDataTemplate
的佣金和一个DataTemplate
用于产品:
Only one HierarchicalDataTemplate
of Commission is required and one DataTemplate
for Product:
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type m:Commission}"
ItemsSource="{Binding Products}">
<TextBlock Text="{Binding Id}" />
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type m:Product}">
<TextBlock Text="{Binding Code}" />
</DataTemplate>
</TreeView.Resources>
说明:
- 为需要包含子节点的节点声明
HierarchicalDataTemplate
.在您的情况下,佣金. - 将
ItemsSource
设置为您需要在这些节点下方显示的子集合.在您的情况下Products
. - 最后,为不包含任何子节点的节点声明
DataTemplate
.就您而言,产品.
- Declare
HierarchicalDataTemplate
for nodes which needs to contain child nodes. In your case Commission. - Set
ItemsSource
to child collection which you need to shown beneath those nodes. In your caseProducts
. - Lastly, declare
DataTemplate
for node which won't contain any child nodes. In your case Product.
这篇关于WPF TreeView 数据绑定跟进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!