title: Get parent TreeViewItem of a selected node in WPF
body: <p>I want the parent of a node that is selected as TreeViewItem</p>
  
  <p>I have a Person class with 2 fields. Name(String) and Children(List of string)</p>
  
  <p>This is my xaml code</p>
  
  <pre><code>&lt;Grid x:Name="gridView" Margin="10"&gt;
      &lt;TreeView Name="treeView1" TreeViewItem.Selected="TreeViewItem_OnItemSelected" ItemsSource="{Binding}"&gt;
          &lt;TreeView.ItemContainerStyle&gt;
              &lt;Style TargetType="{x:Type TreeViewItem}"&gt;
                  &lt;Setter Property="IsSelected" Value="{Binding IsSelected, Source=Check, Mode=TwoWay}" /&gt;
              &lt;/Style&gt;
          &lt;/TreeView.ItemContainerStyle&gt;
          &lt;TreeView.Resources&gt;
              &lt;HierarchicalDataTemplate DataType="{x:Type loc:Person}" ItemsSource="{Binding Children}" &gt;
                  &lt;TextBlock Text="{Binding Name}" /&gt;
              &lt;/HierarchicalDataTemplate&gt;
          &lt;/TreeView.Resources&gt;
      &lt;/TreeView&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p>this is my code behind.
  I set the item source to a list of Person objects.</p>
  
  <pre><code>void set()
  {
      if (treeView1.Items.IndexOf(treeView1.SelectedItem) != -1)
      {
          //is a parent 
          //returns -1 for children
          Person selected = (Person)treeView1.SelectedItem;
          int index = search(selected);
          TreeViewItem parent = treeView1.Tag as TreeViewItem;
          setSelected(parent,index);
      }
      else
      {
          //is a child
          TreeViewItem child = treeView1.Tag as TreeViewItem; //returns the selected node
          TreeViewItem parent = child.Parent as TreeViewItem; //returns null
      }
  }
  private void TreeViewItem_OnItemSelected(object sender, RoutedEventArgs e)
  {
      treeView1.Tag = e.OriginalSource;
      int ind = 0;
      foreach (var _item in treeView1.Items)
      {
          if (_item == treeView1.SelectedItem)
          {
              selectedIndex = ind;
              break;
          }
          ind++;
      }
  }
  </code></pre>
  
  <p>In the else part, The <code>child.Parent</code> always returns null. I tried other methods but none of them return a <code>TreeViewItem</code> instead they return <code>DependencyObject</code> or <code>ItemsControl</code>.</p>
  
  <p>I also tried <code>ContainerFromItem</code> method but it only works for direct children(parent) and not the children of the parent. </p>
  
  <p>Please help</p>