1

I am trying to use WPF TreeView to create a hierarchy in my application, I am trying to create a hierarchy as follows:

Obj A
-Obj B
--Obj C
---Obj D
----Obj E
---Obj D
----Obj E

In essence each of the objects in the hierarchy above with different letters are different types of objects which all inherit from an abstract class to share common properties.

One of this these common properties is a List which contains the children of that particular node.

After browsing some online tutorials and forums, I have had some difficulty in creating the hierarchy using HierarchicalDataTemplate XAML attributes.

At the moment I am using the following XAML:

<TreeView x:Name="treeviewProjectStructure" Grid.Row="1" Margin="2" SelectedItemChanged="treeviewProjectStructure_SelectedItemChanged" ItemsSource="{Binding Nodes}">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:Node}" ItemsSource="{Binding Children.Name}">
                <TextBlock Text="{Binding Name}"></TextBlock>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
</TreeView>

In the example above "Nodes" is a ObservableCollection which holds all the nodes which is declared in the MainWindow.cs

Using this XAML simply displays the root node without any children nodes.

Any help would be much appreciated, thanks :)

1 Answer 1

1

The ItemsSource in your HierarchicalDataTemplate is wrong, you should bind to Children, not Children.Name:

... ItemsSource="{Binding Children}"

Also, you should set the HierarchicalDataTemplate as the TreeView's ItemTemplate, rather than in the resources:

<TreeView x:Name="treeviewProjectStructure" Grid.Row="1" Margin="2" SelectedItemChanged="treeviewProjectStructure_SelectedItemChanged" ItemsSource="{Binding Nodes}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="{x:Type local:Node}" ItemsSource="{Binding Children}">
                <TextBlock Text="{Binding Name}"></TextBlock>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
</TreeView>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your response, when I implement what you suggested, the TreeView only displays the parent node with no children. To give some further information, each node has a List which contains details of the child node.
@andrewjameswatt, you do have a Children property in your Node class, right ?
Yes, Node class contains a Dictionary object which holds children.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.