Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treeview ContainerFromItem always returns null

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?

like image 939
ConditionRacer Avatar asked Jul 15 '11 19:07

ConditionRacer


1 Answers

Is the item actually a child of the masterTreeView?

This might actually be quite difficult since TreeViewItems are ItemsControls with their own ItemContainerGenerator which means you should only be able to get the container from the immediate parent's ItemContainerGenerator 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.

like image 177
H.B. Avatar answered Sep 19 '22 14:09

H.B.