HierarchicalDataTemplate
is supposed to do that for you. You only need to define it once in TreeView
's DataTemplate
.
I think we only need to bind HierachicalDataTemplate
's ItemsSource
into the nested property of your class and it will take care of the rest.
If I misunderstood something about your intention, please let me know.
Here's my attempt:
XAML
<TreeView ItemsSource="{Binding Branches}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Branches}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding Id}"></TextBox>
<TextBox Grid.Column="1" Text="{Binding Name}"></TextBox>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
A class with nested collection
public class Branch
{
public string Id { get; set; }
public string Name { get; set; }
public ObservableCollection<Branch> Branches { get; set; }
}
Hard coded value in main form for testing purpose
public partial class MainWindow : Window
{
public Branch Branch { get; set; }
public MainWindow()
{
Branch = new Branch()
{
Id = "1",
Name = "A",
Branches = new ObservableCollection<Branch>()
{
new Branch()
{
Id = "2",
Name = "B",
Branches = new ObservableCollection<Branch>()
{
new Branch()
{
Id = "3",
Name = "C",
},
new Branch()
{
Id = "3",
Name = "C",
Branches = new ObservableCollection<Branch>()
{
new Branch()
{
Id = "3",
Name = "C",
},
new Branch()
{
Id = "3",
Name = "C",
}
}
}
}
},
new Branch()
{
Id = "2",
Name = "B",
Branches = new ObservableCollection<Branch>()
{
new Branch()
{
Id = "3",
Name = "C",
}
}
}
}
};
InitializeComponent();
this.DataContext = this.Branch;
}
}
Result
