title: WPF cannot get ItemContainerGenerator.ContainerFromItem to work
body: <p>I have looked <a href="https://stackoverflow.com/questions/6713365/itemcontainergenerator-containerfromitem-returns-null">here</a> and <a href="https://stackoverflow.com/questions/1000040/selecteditem-in-a-wpf-treeview">here</a> and many other places, but I just can't seem to get the <code>ItemContainerGenerator.ContainerFromItem</code> method to work on a WPF TreeView!  I have tried to pass in the actual item I want to see, but not getting anywhere with that, I just tried to get the first item in my TreeView.  Here's my sample code:</p>
  
  <pre><code>private static bool ExpandAndSelectItem(ItemsControl parentContainer, object itemToSelect)
  {
      // This doesn't work.
      parentContainer.BringIntoView();
      // May be virtualized, bring into view and try again.
      parentContainer.UpdateLayout();
      parentContainer.ApplyTemplate();
  
      TreeViewItem topItem = (TreeViewItem)parentContainer.ItemContainerGenerator.ContainerFromItem(parentContainer.Items[0]);
  
      // Can't find child container unless the parent node is Expanded once
      if ((topItem != null) &amp;&amp; !topItem.IsExpanded) 
      {
          topItem.IsExpanded = true;
          parentContainer.UpdateLayout();
      }
  }
  </code></pre>
  
  <p>As you can see, I have tried to call many "updating" methods to try to get the TreeView to be "visible" and "accessible".  The Catch-22 seems to be that you can't use <code>ContainerFromItem()</code> unless the first TreeViewItem is expanded, but I can't grab the TreeViewItem to Expand it until <code>ContainerFromItem()</code> works!</p>
  
  <p>Another funny thing that is happening is this:  When I open this window (it is a UserControl), <code>ContainerFromItem()</code> returns nulls, but if I close the window and open it back up, <code>ContainerFromItem()</code> starts returning non-nulls.  Is there any event I should be looking for or forcing to fire?</p>