Reputation: 585
I need to create a TreeView with an infinite parent-child hierarchy. The TreeView needs to be bound to a list named ResourceList
and draws its child resources from a list named Children
. All the items are the same type.
Here is the XAML code I have so far:
<TreeView ItemsSource="{Binding ResourceList}" Grid.Column="0" Grid.Row="2" x:Name="ResourcesTree" SelectedItemChanged="ResourcesTree_OnSelectedItemChanged" Margin="0,4,0,0">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
It works, but the problem is, it only goes three levels deep. What should I change to make it infinite?
In case it's important, I'm using C# and .NET for the code-behind.
Upvotes: 4
Views: 1783
Reputation: 778
You Treeview should look like this:
<TreeView ItemsSource="{Binding ResourceList}" Grid.Column="0" Grid.Row="2" x:Name="ResourcesTree" SelectedItemChanged="ResourcesTree_OnSelectedItemChanged" Margin="0,4,0,0">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type childType}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</HierachicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Note childType
should be whatever class your tree is made up of.
The important part is the DataType="{x:Type childType}"
which makes sure that all children (and grandchildren, etc..) use this datatemplate and it handles hierarchical aspect of it for you
Upvotes: 6