One thing you could consider is taking a path based approach to locating the tree node, like Main\Test Category B\B.1\T1 for example:
private TreeViewItem? FindItemByPath(TreeView treeView, string path)
{
string[] nodes = path.Split(Path.DirectorySeparatorChar);
ItemsControl currentLevel = treeView;
foreach (string header in nodes)
{
bool found = false;
foreach (var item in currentLevel.Items)
{
if (item is TreeViewItem treeViewItem && treeViewItem.Header.ToString() == header)
{
currentLevel = treeViewItem;
found = true;
break;
}
}
if (!found)
{
return null;
}
}
return currentLevel as TreeViewItem;
}
Regardless of how you find the item, what you then want to next is iterate up and expand all its parents.
private void SelectItem(TreeViewItem item)
{
var parent = VisualTreeHelper.GetParent(item);
while (parent is TreeViewItem parentItem)
{
parentItem.IsExpanded = true;
parent = VisualTreeHelper.GetParent(parentItem);
}
item.IsSelected = true;
item.BringIntoView();
}
