本文介绍了如何通过后台编程,在点击按钮【全部展开】和【全部收缩】时实现 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)); } } } }
参考资料: