If the classes are as follows:
public class FatherClass { public string Name { get; set; } public List<ChildClass> Children { get; set; } } public class ChildClass { public string Name { get; set; } }
and in ctor window i have the following data:
List<FatherClass> list = new List<FatherClass>(); list.Add(new FatherClass { Name = "First Father" }); list.Add(new FatherClass { Name = "Second Father" }); list[0].Children = new List<ChildClass>(); list[1].Children = new List<ChildClass>(); list[0].Children.Add(new ChildClass { Name = "FirstChild" }); list[0].Children.Add(new ChildClass { Name = "SecondChild" }); list[1].Children.Add(new ChildClass { Name = "ThirdChild" }); list[1].Children.Add(new ChildClass { Name = "ForthChild" }); this.DataContext = list;
then to create a hierarchical data binding you must define two hierarchical data sets in the resources to "capture" the corresponding data types, for example:
<Grid.Resources> <HierarchicalDataTemplate DataType="{x:Type my:FatherClass}" ItemsSource="{Binding Children}" > <TreeViewItem Header="{Binding Name}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type my:ChildClass}" > <TreeViewItem Header="{Binding Name}" /> </HierarchicalDataTemplate> </Grid.Resources>
and then the tree image syntax should be:
<TreeView ItemsSource="{Binding }"> </TreeView>
source share