WPF的TreeView和TreeViewItem都是继承于ItemsControl,通过ItemContainerGenerator来获取TreeViewItem,但是要注意的是如果TreeViewItem未被展开过,则无法通过ItemContainerGenerator来查找这个TreeViewItem下的子节点,所以一定要将TreeViewItem的IsExpanded属性设置为True,并调用UpdateLayout方法。代码如下:
private static TreeViewItem FindTreeViewItem(ItemsControl item, object data)
{
TreeViewItem findItem = null;
bool itemIsExpand = false;
if (item is TreeViewItem)
{
TreeViewItem tviCurrent = item as TreeViewItem;
itemIsExpand = tviCurrent.IsExpanded;
if (!tviCurrent.IsExpanded)
{
//如果这个TreeViewItem未展开过,则不能通过ItemContainerGenerator来获得TreeViewItem
tviCurrent.SetValue(TreeViewItem.IsExpandedProperty, true);
//必须使用UpdaeLayour才能获取到TreeViewItem
tviCurrent.UpdateLayout();
}
}
for (int i = 0; i < item.Items.Count; i++)
{
TreeViewItem tvItem = (TreeViewItem)item.ItemContainerGenerator.ContainerFromIndex(i);
if (tvItem == null)
continue;
object itemData = item.Items[i];
if (itemData == data)
{
findItem = tvItem;
break;
}
else if (tvItem.Items.Count > 0)
{
findItem = FindTreeViewItem(tvItem, data);
if (findItem != null)
break;
}
}
if (findItem == null)
{
TreeViewItem tviCurrent = item as TreeViewItem;
tviCurrent.SetValue(TreeViewItem.IsExpandedProperty, itemIsExpand);
tviCurrent.UpdateLayout();
}
return findItem;
}
在调用方法:
FindTreeViewItem(tvData,data);
其中tvData就是TreeView控件的名称,data是TreeView绑定的对象。也就是TreeView的Items属性中包含的对象。
转载自:http://blog.163.com/lai_xiao_hui/blog/static/1230373242013111713015876/