如何实现 TreeView Items 全部展开和全部收缩(WPF)

本文介绍了如何通过后台编程,在点击按钮【全部展开】和【全部收缩】时实现 TreeView 所有节点的展开与收缩。

程序如下:

// 全部收缩
private void btnCollapseAll_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in treeView.Items)
        {
            DependencyObject dObject = treeView.ItemContainerGenerator.ContainerFromItem(item);
            CollapseTreeviewItems(((TreeViewItem)dObject));
        }
    }

// 全部展开
    private void btnExpandAll_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in treeView.Items)
        {
            DependencyObject dObject = treeView.ItemContainerGenerator.ContainerFromItem(item);
            ((TreeViewItem)dObject).ExpandSubtree();
        }
    }

    private void CollapseTreeviewItems(TreeViewItem Item)
    {
        Item.IsExpanded = false;

        foreach (var item in Item.Items)
        {
            DependencyObject dObject = treeView.ItemContainerGenerator.ContainerFromItem(item);

            if (dObject != null)
            {
                ((TreeViewItem)dObject).IsExpanded = false;

                if (((TreeViewItem)dObject).HasItems)
                {
                    CollapseTreeviewItems(((TreeViewItem)dObject));
                }
            }
        }
    }







参考资料:

1.How to expand items in a TreeView – Part II

2.Expanded all WPF Treeview Items

posted @ 2015-11-24 20:13  贱贱的梦想  阅读(3453)  评论(0编辑  收藏  举报