Treeview 没有显示我的孩子 [英] Treeview not showing my children
问题描述
我之前没有使用过 TreeView,只是在一些教程中使用过它们来掌握它们.我以为我有,结果我没有.
I've not used the TreeView before other than in a few tutorials to get the hang of them. I thought I had, it turns out I haven't.
我正在尝试将我的 TreeView 绑定到一个对象.
I'm trying to bind my TreeView to an object.
对象是
public List<MyGrandparents> MyGrandParents {get;set;}
在 MyGrandParent 类中,有一个属性
Within the MyGrandParent class, there is a property
public List<MyParents> MyParents{get;set;}
最后,在 MyParent 类中有一个属性
and lastly, within the MyParent class there is a property
public List<MyChildren> MyChildren {get;set;}
在每个类中,还有其他属性,例如 Name(虽然没有基类,因此在此阶段没有共享代码)
Within each class, there are other properties such as Name (no base classes though so no shared code at this stage)
我想将地块绑定到树视图,因此在根"级别我只能看到祖父母.我可以扩大祖父母只看到父母,我也可以扩大他们看到孩子.
I want to bind the lot to a tree view, so at 'root' level I only see grandparents. I can expand grandparents to only see parents, whom I can also expand to see children.
我遇到的问题只是最高级别的绑定(祖父母级别).我的 XAML 是
The issue I have is only the highest level is binding (grandparent level). My XAML is
<TreeView ItemsSource="{Binding MyGrandParents}">
<TreeView.Resources>
<DataTemplate DataType="{x:Type local:MyGrandParent}">
<TextBlock Text="{Binding Name}" Margin="0,0,10,0" />
</DataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MyParent}" ItemsSource="{Binding MyGrandParents}">
<TextBlock Text="Don't bind to test"></TextBlock>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
我不明白为什么这不能给我一棵漂亮的树.
I am lost as to why this isn't binding to give me a nice Tree.
推荐答案
您没有遵循正确的模式来使用 HierarchicalDataTemplate
.
You are not following correct pattern to use HierarchicalDataTemplate
.
可能包含子项
的项目应声明为HierarchicalDataTemplate
,并将ItemsSource
设置为您想要的child collection
显示在它下面.
Item which might contain children
should be declare as HierarchicalDataTemplate
with ItemsSource
set to child collection
you want to show beneath it.
并且item不包含任何子
应该声明为DataTemplate
.
应该是这样-
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:MyGrandParent}"
ItemsSource="{Binding MyParents}">
<TextBlock Text="{Binding Name}" Margin="0,0,10,0" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MyParent}"
ItemsSource="{Binding MyChildren}">
<TextBlock Text="Don't bind to test"></TextBlock>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:MyChildren}">
<TextBlock Text="Don't bind to test"></TextBlock>
</DataTemplate>
</TreeView.Resources>
这篇关于Treeview 没有显示我的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!