AutoExpand treeview in WPF

前端 未结 5 2068
悲哀的现实
悲哀的现实 2021-02-06 21:04

Is there a way to automatically expand all nodes from a treeview in WPF? I searched and didn\'t even find an expand function in the treeview property.

Thanks

5条回答
  •  一整个雨季
    2021-02-06 21:39

    This is what I use:

    private void ExpandAllNodes(TreeViewItem rootItem)
    {
        foreach (object item in rootItem.Items)
        {
            TreeViewItem treeItem = (TreeViewItem)item;
    
            if (treeItem != null)
            {
                ExpandAllNodes(treeItem);
                treeItem.IsExpanded = true;
            }
        }
    }
    

    In order for it to work you must call this method in a foreach loop for the root node:

    // this loop expands all nodes
    foreach (object item in myTreeView.Items)
    {
        TreeViewItem treeItem = (TreeViewItem)item;
    
        if (treeItem != null)
        {
            ExpandAllNodes(treeItem);
            treeItem.IsExpanded = true;
        }
    }
    

提交回复
热议问题