Dave
Dave

Reputation: 8461

Treeview not showing my children

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.

I'm trying to bind my TreeView to an object.

The Object is

public List<MyGrandparents> MyGrandParents {get;set;}

Within the MyGrandParent class, there is a property

public List<MyParents> MyParents{get;set;}

and lastly, within the MyParent class there is a property

public List<MyChildren> MyChildren {get;set;}

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.

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.

Upvotes: 0

Views: 963

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81243

You are not following correct pattern to use HierarchicalDataTemplate.

Item which might contain children should be declare as HierarchicalDataTemplate with ItemsSource set to child collection you want to show beneath it.

And item not containing any child should be declare as DataTemplate instead.

It should be like this -

<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>

Upvotes: 3

Related Questions