title: Expanding/selecting a treeview node when it is not currently visible
body: <p>I have a requirement to change the selected node in a treeview which is hosted in a separate tab.
  Further more, if the parent node is not expanded, I wish to expand the node.</p>
  
  <p>After about an hour of fruitless searching through SO, Google, et al, I have decided to post a question.</p>
  
  <p>I can find and expand the required node when it is all visible, but when the treeveiw is obscured by another tab item, it doesn't update. I'm also not entirely sure that the item is being 'selected' - in the debugger it says ISelected is true, and the IsExpanded property of the parent is also true.</p>
  
  <p>I have simplified down my actual problem in the following lines of code:</p>
  
  <p>XAML (Tab control which has two items, one is a button to reproduce the problem, and a treeview which should be updated):</p>
  
  <pre><code>&lt;Window x:Class="TreeviewTest.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="MainWindow" Height="350" Width="525"&gt;
  &lt;Grid&gt;
      &lt;TabControl&gt;
          &lt;TabItem Header="Select"&gt;
              &lt;Button Content="Select Delta!" Click="ButtonBase_OnClick" /&gt;
          &lt;/TabItem&gt;
          &lt;TabItem Header="Tree"&gt;
              &lt;TreeView ItemsSource="{Binding NodesDisplay}" Name ="treTest"&gt;
                  &lt;TreeView.ItemTemplate&gt;
                      &lt;HierarchicalDataTemplate ItemsSource="{Binding Path=ChildrenDisplay}"&gt;
                          &lt;TextBlock Text="{Binding Path=Name}" FontWeight="Bold" /&gt;
                          &lt;HierarchicalDataTemplate.ItemTemplate&gt;
                              &lt;HierarchicalDataTemplate&gt;
                                  &lt;TextBlock Text="{Binding Path=Name}" /&gt;
                              &lt;/HierarchicalDataTemplate&gt;
                          &lt;/HierarchicalDataTemplate.ItemTemplate&gt;
                      &lt;/HierarchicalDataTemplate&gt;
                  &lt;/TreeView.ItemTemplate&gt;
              &lt;/TreeView&gt;
  
          &lt;/TabItem&gt;
      &lt;/TabControl&gt;
  
  &lt;/Grid&gt;
  </code></pre>
  
  <p></p>
  
  <p>MainWindow code:</p>
  
  <pre><code>namespace TreeviewTest
  {
      using System.Collections.Generic;
      using System.Collections.ObjectModel;
      using System.ComponentModel;
      using System.Linq;
      using System.Reflection;
      using System.Windows;
      using System.Windows.Controls;
      using System.Windows.Controls.Primitives;
      using System.Windows.Data;
  
      /// &lt;summary&gt;
      /// Interaction logic for MainWindow.xaml
      /// &lt;/summary&gt;
      public partial class MainWindow 
      {
          public ObservableCollection&lt;TreeNode&gt; Nodes { get; set; }
  
          public ICollectionView NodesDisplay { get; set; }
  
          public MainWindow()
          {
              InitializeComponent();
  
              Nodes = new ObservableCollection&lt;TreeNode&gt;
              {
                  new TreeNode(new List&lt;TreeLeaf&gt;
                      {
                          new TreeLeaf{Name = "Alpha"},
                          new TreeLeaf{Name = "Beta"}
                      }){ Name = "One" },
                  new TreeNode(new List&lt;TreeLeaf&gt;
                      {
                          new TreeLeaf{Name = "Delta"},
                          new TreeLeaf{Name = "Gamma"}
                      }){ Name = "Two" }
  
              };
              NodesDisplay = CollectionViewSource.GetDefaultView(Nodes);
              DataContext = this;
          }
  
          public class TreeNode
          {
              public string Name { get; set; }
              public ObservableCollection&lt;TreeLeaf&gt; Children { get; private set; }
  
              public ICollectionView ChildrenDisplay { get; private set; }
  
              public TreeNode(IEnumerable&lt;TreeLeaf&gt; leaves)
              {
                  Children = new ObservableCollection&lt;TreeLeaf&gt;(leaves);
                  ChildrenDisplay = CollectionViewSource.GetDefaultView(Children);
              }
          }
  
          public class TreeLeaf
          {
              public string Name { get; set; }
          }
  
          private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
          {
              EnsureCanIterateThroughCollection(treTest);
              var rootLevelToSelect = Nodes.First(x =&gt; x.Name == "Two");
              TreeViewItem root = treTest.ItemContainerGenerator.ContainerFromItem(rootLevelToSelect) as TreeViewItem;
  
              EnsureCanIterateThroughCollection(root);
              var leafLevelToSelect = rootLevelToSelect.Children.First(x =&gt; x.Name == "Delta");
              TreeViewItem leaf = root.ItemContainerGenerator.ContainerFromItem(leafLevelToSelect) as TreeViewItem;
  
              if (!root.IsExpanded)
                  root.IsExpanded = true;
  
              leaf.IsSelected = true;
              ReflectivelySelectTreeviewItem(leaf);
          }
  
          //Got this from another SO post - not sure is setting IsSelected on the node is actually doing what I think it is...
          private static void ReflectivelySelectTreeviewItem(TreeViewItem node)
          {
              MethodInfo selectMethod = typeof(TreeViewItem).GetMethod("Select", BindingFlags.NonPublic | BindingFlags.Instance);
              selectMethod.Invoke(node, new object[] { true });
          }
  
          private static void EnsureCanIterateThroughCollection(ItemsControl itemsControl)
          {
              if (itemsControl.ItemContainerGenerator.Status == GeneratorStatus.NotStarted)
              ForceGenerateChildContent(itemsControl);
          }
  
          private static void ForceGenerateChildContent(ItemsControl itemsControl)
          {
              itemsControl.ApplyTemplate();
  
              IItemContainerGenerator generator = itemsControl.ItemContainerGenerator;
  
              GeneratorPosition position = generator.GeneratorPositionFromIndex(0);
              using (generator.StartAt(position, GeneratorDirection.Forward, true))
              {
                  for (int i = 0; i &lt; itemsControl.Items.Count; i++)
                  {
                      DependencyObject dp = generator.GenerateNext();
                      generator.PrepareItemContainer(dp);
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>Also - another XAML snippet which does the same thing, but where the treeview is visible - you should be able to see the treeview expand and the item selected</p>
  
  <pre><code>&lt;Window x:Class="TreeviewTest.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="MainWindow" Height="350" Width="525"&gt;
  &lt;Grid&gt;
      &lt;Grid.RowDefinitions&gt;
          &lt;RowDefinition Height="30" /&gt;
          &lt;RowDefinition Height="*" /&gt;
      &lt;/Grid.RowDefinitions&gt;
      &lt;Button Content="Select Delta!" Click="ButtonBase_OnClick" /&gt;
      &lt;TreeView ItemsSource="{Binding NodesDisplay}" Name ="treTest" Grid.Row="1"&gt;
          &lt;TreeView.ItemTemplate&gt;
              &lt;HierarchicalDataTemplate ItemsSource="{Binding Path=ChildrenDisplay}"&gt;
                  &lt;TextBlock Text="{Binding Path=Name}" FontWeight="Bold" /&gt;
                  &lt;HierarchicalDataTemplate.ItemTemplate&gt;
                      &lt;HierarchicalDataTemplate&gt;
                          &lt;TextBlock Text="{Binding Path=Name}" /&gt;
                      &lt;/HierarchicalDataTemplate&gt;
                  &lt;/HierarchicalDataTemplate.ItemTemplate&gt;
              &lt;/HierarchicalDataTemplate&gt;
          &lt;/TreeView.ItemTemplate&gt;
      &lt;/TreeView&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p></p>
  
  <p>I would appreciate any help - My understanding of treeview's and WPF and databinding is that it doesn't work as nicely as something that gives you IsSynchronisedWithCurrentItem, which is why I am trying to handle updates to the treeview manually and am also trying to select items in the tree programmatically. If I am wrong on that front I would love a pointer to show me how to do it in a more 'WPF' way!</p>