I want to add a child item in a TreeViewItem that was added previously. The problem with code like this:
How to insert a child node in a TreeView Control in WPF?
You are getting String
because that is what the source of the TreeView
must have been bound to.
Using this method allows you to iterate over the items and retrieve the TreeViewItem
containers that they are inside:
List GetChildren(TreeViewItem parent)
{
List children = new List();
if (parent != null)
{
foreach (var item in parent.Items)
{
TreeViewItem child = item as TreeViewItem;
if (child == null)
{
child = parent.ItemContainerGenerator.ContainerFromItem(child) as TreeViewItem;
}
children.Add(child);
}
}
return children;
}
Please notice that they check if the TreeViewItem is null after casting it. This is good practice as it prevents the null reference exception from crashing your application if something does happen to go wrong.
source: https://social.msdn.microsoft.com/Forums/vstudio/en-US/595f0c84-01e7-4534-b73b-704b41713fd5/traversing-the-children-of-a-treeviewitem