You could add an extension like this for your Custom Control, and make use of the following Expand/Collapse Method
public static class TreeViewExt
{
public static void ExpandRecursively(this ItemsControl itemsControl, bool expand, int levelDepth)
{
int depth = levelDepth == int.MaxValue ? levelDepth : levelDepth - 1;
TreeViewItem treeViewItem = itemsControl as TreeViewItem;
if (treeViewItem != null)
treeViewItem.IsExpanded = expand || levelDepth >= 0; // expand, or keep expanded when levelDepth >= 0
if (levelDepth > 0 || !expand)
{
// get container generator of itemsControl
ItemContainerGenerator itemContainerGenerator = itemsControl.ItemContainerGenerator;
// if containers have already been generated, the subItems can be expanded/collapsed
if (itemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
for (int i = itemsControl.Items.Count - 1; i >= 0; --i)
{
ItemsControl childControl = itemContainerGenerator.ContainerFromIndex(i) as ItemsControl;
if (childControl != null)
childControl.ExpandRecursively(expand, depth);
}
}
else
{
EventHandler handler = null; // store in variable, so the handler can be detached
handler = new EventHandler((s, e) =>
{
if (itemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
for (int i = itemsControl.Items.Count - 1; i >= 0; --i)
{
ItemsControl childControl = itemContainerGenerator.ContainerFromIndex(i) as ItemsControl;
if (childControl != null)
childControl.ExpandRecursively(expand, depth);
itemContainerGenerator.StatusChanged -= handler; // detach
}
}
});
itemContainerGenerator.StatusChanged += handler; // attach
}
}
}
}
Complete Code: Treeview Recursive Expand/Collapse
EDIT:
Since OP wanted to do it for WinForm UserControl, You could loop through the Child Controls using the method like this,
private IEnumerable<Node> getAllNodesRecursively(Node subnode)
{
// Return the parent before its children
yield return subnode;
foreach (Node node in subnode.Nodes)
{
foreach(Node n in getAllNodesRecursively(node))
{
yield return n;
}
}
}
Recursion with yield return elements order in tree