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