Why does the function only work when you press the menu?
If you press the menu, the tree restores the expansion of the branches.
But the same function, starting at the end of the public Window1 () behaves strangely. On the first pass, ExpandRecursively__Load (tw_tree); it turns out the empty contents of tw_tree {System.Windows.Controls.TreeView Items.Count:0} . But for some reason, after the ExpandRecursively__Load is completed, the ExpandRecursively__LoadClick is started again. And it is no longer empty {System.Windows.Controls.TreeView Items.Count:**1**} But all the same if (treeViewItem != null) is always null.
Menu
Main
public partial class Window1 : Window { public Window1() { ... ExpandRecursively__LoadClick(null, null); } This restores the folded branches from the save.
public void ExpandRecursively__LoadClick(object sender, RoutedEventArgs e) { ExpandRecursively__Load(tw_tree); } .
private static void ExpandRecursively__Load(ItemsControl itemsControl) { ItemContainerGenerator itemContainerGenerator = itemsControl.ItemContainerGenerator; for (int i = itemsControl.Items.Count - 1; i >= 0; --i) { ItemsControl childControl = itemContainerGenerator.ContainerFromIndex(i) as ItemsControl; if (childControl != null) { ExpandRecursively__Load(childControl); } } TreeViewItem treeViewItem = itemsControl as TreeViewItem; //при вызове функции через меню, treeViewItem не равно null //при вызове функции из кода, treeViewItem всегда равно null if (treeViewItem != null) { treeViewItem.IsExpanded = ((Node)treeViewItem.DataContext).expanded; } }