WPF Treeview只展开到一定深度?
问题描述:
我有一个数据绑定的TreeView。我想展开TreeViewItems,但只能深入一下让我说3。WPF Treeview只展开到一定深度?
通常我会发出一个TreeViewItem.ExpandSubtree(),但它扩展了一切,所以我采取了刺我自己的,因为它应该是相当简单的权利?
这里是我试过了,我做了下面的方法,然后ItemContainerGenerator通过我的树视图它和收集物品从树视图,用3
private void ExpandTree(ItemContainerGenerator gen, ItemCollection items, int depth)
{
depth--;
foreach (var item in items)
{
TreeViewItem itm = (TreeViewItem)gen.ContainerFromItem(item);
if (itm == null) continue;
itm.IsExpanded = true;
if(depth!=0 && itm.Items.Count > 0) ExpandTree(itm.ItemContainerGenerator,itm.Items,depth);
}
}
问题的深度是第一它递归调用返回ItemContainerGenerator的所有子项都具有“NotStarted”状态,并在每次调用时返回null。虽然我陷入空值意味着树只能打开到1的深度,而不是我想要的3。
我在这里错过了什么?
答
您错过了延迟时间,以便让子ItemContainerGenerator有时间创建孙辈。该解决方案是要求WPF调度安排递归调用后数据绑定的基础设施有时间来运行:现在
Action recurse =() => ExpandTree(itm.ItemContainerGenerator, itm.Items, depth);
itm.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, recurse); // note the priority
,通过委托被调用时,ItemContainerGenerator将有足够的时间运行,容器将可用。
您可能也可以通过订阅子项ItemContainerGenerator的StatusChanged事件(并从那里进行递归调用)来完成此操作,但我没有尝试过这种方法。