title: How to select TreeView item from code
body: <p>I have a three level treeview. How do I select any item in third level from code? I tried a method mentioned in many blogs and on stackoverflow but it seems to work only for first level (dbObject is null for items on below first level). </p>
  
  <p>Here is the code I'm using to select TreeViewItem. Do I miss something? </p>
  
  <pre><code>public static void SetSelectedItem(this TreeView control, object item)
  {
      try
      {
          var dObject = control.ItemContainerGenerator.ContainerFromItem(item);
  
          //uncomment the following line if UI updates are unnecessary
          ((TreeViewItem)dObject).IsSelected = true;
  
          MethodInfo selectMethod = typeof(TreeViewItem).GetMethod("Select",
              BindingFlags.NonPublic | BindingFlags.Instance);
  
          selectMethod.Invoke(dObject, new object[] { true });
      }
      catch { }
  }
  </code></pre>