WPF TreeView: Where is the ExpandAll() method

后端 未结 7 2106
抹茶落季
抹茶落季 2020-12-30 19:06

How can I expand all TreeView nodes in WPF? In WinForms there was a ExpandAll() method which does this.

7条回答
  •  清歌不尽
    2020-12-30 19:41

    The answer provided by @Pierre-Olivier is a good one.

    Personally, I prefer to use a stack rather than recursion in circumstances such as these where you have no idea how deeply nested the data could be. Even better, it could be provided as an extension function:

    public static void ExpandAll(this TreeViewItem treeViewItem, bool isExpanded = true)
    {
        var stack = new Stack(treeViewItem.Items.Cast());
        while(stack.Count > 0)
        {
            TreeViewItem item = stack.Pop();
    
            foreach(var child in item.Items)
            {
                var childContainer = child as TreeViewItem;
                if(childContainer == null)
                {
                    childContainer = item.ItemContainerGenerator.ContainerFromItem(child) as TreeViewItem;
                }
    
                stack.Push(childContainer);
            }
    
            item.IsExpanded = isExpanded;
        }
    }
    
    public static void CollapseAll(this TreeViewItem treeViewItem)
    {
        treeViewItem.ExpandAll(false);
    }
    

提交回复
热议问题