Try doing the following. Build a class that the Tree
can bind to. The only property is a populated list of parents. The list would be normally populated from a database.
public class FamiliesVM
{
public List<Parent> FamilyList { get; private set; }
public FamiliesVM()
{
FamilyList = new List<Parent>
{
new Parent
{
Id = 1,
Name = "A",
Children = new List<Child> { new Child { Id=1,Name="AA"},
new Child { Id=2,Name="AB"},new Child { Id=3,Name="AC"} }
},
new Parent
{
Id = 2,
Name = "B",
Children = new List<Child> { new Child { Id=4,Name="BA"},
new Child { Id=5,Name="BB"},new Child { Id=6,Name="BC"} }
},
new Parent
{
Id = 3,
Name = "C",
Children = new List<Child> { new Child { Id=7,Name="CA"},
new Child { Id=8,Name="CB"},new Child { Id=9,Name="CC"} }
}
};
}
}
The
Parent
class is defined something like this
public class Parent
{
public string Name { get; set; }
public int Id { get; set; }
public List<Child> Children { get; set; }
}
In the
XAML
, set the
DataContext
to
FamiliesVM
. Have a
HierarchicalDataTemplate
that defines the source for the node as
Parent
and the source for the children of the node as the
Children
property of the
Parent
. Have a
DataTemplate
that details how a
Child
instance should be displayed. Set the TreeView source to the
FamilyList
property of the
FamiliesVM
. That should do the trick.
<Window x:Class="FamilyTree.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FamilyTree"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:FamiliesVM />
</Window.DataContext>
<DockPanel>
<DockPanel.Resources>
<HierarchicalDataTemplate DataType = "{x:Type local:Parent}"
ItemsSource = "{Binding Path=Children}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:Child}">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</DockPanel.Resources>
<TreeView>
<TreeViewItem ItemsSource="{Binding FamilyList}" Header="Parent and Children" />
</TreeView>
</DockPanel>
</Window>