@JROs塌陷他們1 answer將無法正常工作時,數據綁定到項目,它只會在直接將TreeViewItem
s加入TreeView
。
我提出此擴展方法,該方法將檢索匹配TreeViewItem
用於在迭代的當前對象:
namespace System.Windows.Controls
{
using System.Linq;
public static class TreeViewExtensions
{
public static void SetExpansion(this TreeView treeView, bool isExpanded) =>
SetExpansion((ItemsControl)treeView, isExpanded);
static void SetExpansion(ItemsControl parent, bool isExpanded)
{
if (parent is TreeViewItem tvi)
tvi.IsExpanded = isExpanded;
if (parent.HasItems)
foreach (var item in parent.Items.Cast<object>()
.Select(i => GetTreeViewItem(parent, i, isExpanded)))
SetExpansion(item, isExpanded);
}
static TreeViewItem GetTreeViewItem(
ItemsControl parent, object item, bool isExpanded)
{
if (item is TreeViewItem tvi)
return tvi;
var result = ContainerFromItem(parent, item);
if (result == null && isExpanded)
{
parent.UpdateLayout();
result = ContainerFromItem(parent, item);
}
return result;
}
static TreeViewItem ContainerFromItem(ItemsControl parent, object item) =>
(TreeViewItem)parent.ItemContainerGenerator.ContainerFromItem(item);
}
}
用法:
treeView.SetExpansion(isExpanded: true/false);