Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use data binding to create a TreeView with infinite depth in WPF?

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.

like image 427
Zerbu Avatar asked Sep 20 '25 15:09

Zerbu


1 Answers

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

like image 151
Gordon Allocman Avatar answered Sep 22 '25 05:09

Gordon Allocman