The tree should turn around completely, but only the first level unfolds.
ExpandRecursively2(tw_tree, true); private static void ExpandRecursively2(ItemsControl itemsControl, bool expand) { ItemContainerGenerator itemContainerGenerator = itemsControl.ItemContainerGenerator; for (int i = itemsControl.Items.Count - 1; i >= 0; --i) { TreeViewItem treeViewItem = itemsControl as TreeViewItem; if (treeViewItem != null) treeViewItem.IsExpanded = expand; // ItemsControl childControl = itemContainerGenerator.ContainerFromIndex(i) as ItemsControl; if (childControl != null) ExpandRecursively2(childControl, expand); } } In this strange behavior.
If you add to the menu ExpandRecursively2(tw_tree, true); and press many times.
Then each time the next deeper branch opens.
Here childControl is sometimes 0 . Because of this, the next branch does not go.
Why can it be equal to 0. What is wrong?
ItemsControl childControl = itemContainerGenerator.ContainerFromIndex(i) as ItemsControl;