I've read a few threads on this subject but couldn't find anything to do what I'm trying to do. I have a treeview that is bound to a hierarchical set of objects. Each of these objects represents an icon on a map. When the user clicks one of the icons on the map, I want to select the item in the tree view, focus on it, and scroll it into view. The map object has a list of the objects that are bound to the treeview. In the example, Thing is the type of object bound to the tree.
public void ScrollIntoView(Thing t)
{
if (t != null)
{
t.IsSelected = true;
t.IsExpanded = true;
TreeViewItem container = (TreeViewItem)(masterTreeView
.ItemContainerGenerator.ContainerFromItem(t));
if (container != null)
{
container.Focus();
LogicalTreeHelper.BringIntoView(container);
}
}
}
So far, no matter what I've tried, container is always null. Any ideas?
You have 3 choices: - You disable the virtualization of items: , but this could have impact on performance - You manage itemContainerGenerator status for each item (some code provided as examples). Pretty complex. - You add a hierarchical view model to your hierarchy and implement a "IsExpanded" property to it for each node level. The best solution.
Disable virtualization:
Good Luck...
And
The issue is that each TreeViewItem is itself an ItemsControl so they each manage their own containers for their children.
Is the item actually a child of the
masterTreeView
?This might actually be quite difficult since
TreeViewItems
areItemsControls
with their ownItemContainerGenerator
which means you should only be able to get the container from the immediate parent'sItemContainerGenerator
and not from the root.Some recursive function which first goes up the hierarchy to the root and then reverses this route on the ui level always getting the container of the items might work out but your data-items need a reference to their logical parent data object.