To traverse through a tree, a recursive function is the universal solution. If binding to a WPF tree, I would use ObservableCollection instead of List for the child items. I have made a simple example with a recursive function building up a tree, and then displaying it in a WPF TreeView.
This is the data class:
public class TreeNode {
public ObservableCollection<TreeNode> Children {
get;
} = new ObservableCollection<TreeNode>();
public string Name {
get;set;
}
}
This is the recursive function to fill the tree (it generates 5 generations of children, each parent node having 6 children):
/// <summary>
/// Fill a recursive tree
/// </summary>
/// <param name="node">The treenode to generate children for</param>
/// <param name="depth">Current depth, always incremented by 1 when going deeper in recursion</param>
/// <param name="namePostfix">Name postfix, just for generating display name for the nodes</param>
void fillTree(TreeNode node, int depth, string namePostfix) {
// exit to prevent endless recursion
if (depth >= 5) {
return;
}
for (int i = 0; i < 6; ++i) {
var child = new TreeNode() {
Name = $"Node{namePostfix}{i}"
};
fillTree(child, depth + 1, namePostfix + i);
node.Children.Add(child);
}
}
If you want to traverse the tree, you should write something similar according to the traverse method you choose (from the previous answer).
XAML markup (see this link for a basic tutorial):
<TreeView x:Name="tv">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:TreeNode}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
And in the constructor of the Window/Page:
fillTree(tree, 0, "");
tv.Items.Add(tree); // tv is the x:Name of the TreeView
Of course this is just a simple example, I would use view model and data binding etc, but that is out of the scope of this question.