TDD developer

July 15, 2008

Databinding WPF treeview using recursion

Filed under: .NET — makka @ 9:54 pm
Tags: , ,

Today I solved a very interesting problem using a TreeView and a HierarchicalDataTemplate. My final goal was to display an objects tree using a TreeView control as shown here below.

image

The result is not very nice but wait, I am a developer not a designer!
Ok, less chatter! Let’s look at the code that is much more interesting.
In this case the datasource is a tree composed by a set of Foo objects.
Here is the Foo class definition

public class Foo
{
    public Foo()
    {
        Children = new List<Foo>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<Foo> Children { get; set; }
}

and here a dummy method that create a sample objects tree

public class Service
{
    private readonly Collection<Foo> fooList;

    public IEnumerable<Foo> FooList
    {
        get { return fooList; }
    }

    public Service()
    {
        fooList = new Collection<Foo> { new Foo { Id = 0, Name = "first" }, new Foo { Id = 99, Name = "makka" } };
        fooList[0].Children.Add(new Foo { Id = 1, Name = "second" });
        fooList[0].Children.Add(new Foo { Id = 2, Name = "third" });
        fooList[0].Children[0].Children.Add(new Foo { Id = 3, Name = "fourth" });
    }
}

Until here nothing special.
The interesting part is the XAML markup. As you can see using the power of HierarchicalDataTemplate with few lines of code we can create a recursive loop in order to populate the TreeView starting from a simple IEnumerable<Foo> object

<TreeView Name="viewsTreeView"  >
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type Demo:Foo}" ItemsSource="{Binding Path=Children}">
            <TreeViewItem Header="{Binding Path=Name}"  />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

I hope this sample will save you some time!

1 Comment »

  1. Hi,
    can you explain how do you tell your instance of TreeView (viewsTreeView) that you want instances of Foo class to be taken from Service class ?

    Also notation: ‘Demo:Foo’ in <HierarchicalDataTemplate DataType="{x:Type Demo:Foo}"… is not exactly clear. I guess Demo is a namespace of Foo, what is not noted in the snippet of Foo.

    Thanks in advance

    Zuraff

    Comment by zuraff — June 17, 2009 @ 7:53 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.