我TreeView
用一个根元素创建了一个:
TreeViewControl treeViewConrol = new TreeViewControl(tvVisual,TreeServiceManager);
TreeNode rootNode=GetRootNode();
然后,我将此根元素添加到树中:
treeViewControl.TreeView.Items.Add(rootNode);
并尝试定位项目:
TreeViewControl.LocateItem(ref treeViewConrol.TreeView, rootNode);
public static void LocateItem(ref TreeView treeView, object item)
{
ExpandAndSelectItem(treeView, item);
}
private static bool ExpandAndSelectItem(ItemsControl parentContainer, object itemToSelect)
{
//check all items at the current level
foreach (TreeNode item in parentContainer.Items)
{
TreeViewItem currentContainer = parentContainer.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
//if the data item matches the item we want to select, set the corresponding
//TreeViewItem IsSelected to true
if (item == itemToSelect && currentContainer != null)
{
currentContainer.IsSelected = true;
currentContainer.BringIntoView();
currentContainer.Focus();
//the item was found
return true;
}
}
//cut part shippet's code. You can find it at blog
//no item was found
return false;
}
因此,我从http://blog.quantumbitdesigns.com获取了这段代码片段。但是这条线:
TreeViewItem currentContainer = parentContainer.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
始终为空。
我的观点是从根元素获取容器,获取它的子元素并通过,同时我可以找到元素并展开树。
那么,如何让 currentContainer 不为空呢?
PS我读过Treeview ContainerFromItem 总是返回 null并且TreeView.ItemContainerGenerator.ContainerFromItem 返回 null。