1

I have a object of a class defined below

class XYZ
{
    List<XYZ> child;
    String header;
}

I want to bind this object to a tree view. Initially XYZ root will be the topmost TreeViewItem. root will have the List child as the sub TreeViewItems. This will go on recursively until List of each XYZ object is not empty. Each TreeViewItem is either a node or a leaf (if List child is empty).

I am able to do this programmatically by adding TreeViewItem as a child to parent TreeViewItem.

The number of levels is not known.

I referred this answer Bind Object to WPF TreeView but here it is mentioned for a three level hierachy.

0

1 Answer 1

4

You just need to define the Hierarchical Datatemplate for your viewmodel and that should take care of the multiple levels in your treeview.

Make sure the collection you are using implements INotificationPropertyChanged

The datatemplate will be in the lines of

<TreeView ItemsSource={Binding child}>
<TreeView.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding child}" DataType="{x:Type vm:XYZ}">
<Grid>
<TextBlock Text="{Binding header}"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Sign up to request clarification or add additional context in comments.

1 Comment

Why downvote??? The OP asked how to build a dynamic treeview and I provided a Datatemplate for that. Ofcourse he did not provide any code I had to guess his implementation and provide a guide atleast for a solution!

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.