title: Binding SelectedItem in a HierarchicalDataTemplate-applied WPF TreeView
body: <p>I have a data-bound <code>TreeView</code> and I want to bind <code>SelectedItem</code>. <a href="https://stackoverflow.com/a/5118406/986080">This attached behavior</a> works perfectly without <code>HierarchicalDataTemplate</code> but with it the attached behavior only works one way (UI to data) not the other because now <code>e.NewValue</code> is <code>MyViewModel</code> not <code>TreeViewItem</code>. </p>
  
  <p>This is a code snippet from the attached behavior:</p>
  
  <pre><code>private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
  {
      var item = e.NewValue as TreeViewItem;
      if (item != null)
      {
          item.SetValue(TreeViewItem.IsSelectedProperty, true);
      }
  }
  </code></pre>
  
  <p>This is my <code>TreeView</code> definition:</p>
  
  <pre><code>&lt;Window xmlns:interactivity="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"&gt;
      &lt;TreeView ItemsSource="{Binding MyItems}" VirtualizingStackPanel.IsVirtualizing="True"&gt;
          &lt;interactivity:Interaction.Behaviors&gt;
              &lt;behaviors:TreeViewSelectedItemBindingBehavior SelectedItem="{Binding SelectedItem, Mode=TwoWay}" /&gt;
          &lt;/interactivity:Interaction.Behaviors&gt;
          &lt;TreeView.Resources&gt;
              &lt;HierarchicalDataTemplate DataType="{x:Type local:MyViewModel}" ItemsSource="{Binding Children}"&gt;
                  &lt;TextBlock Text="{Binding Name}"/&gt;
              &lt;/HierarchicalDataTemplate&gt;
          &lt;/TreeView.Resources&gt;
      &lt;/TreeView&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p>If I can get a reference to the <code>TreeView</code> in the attached behavior method <code>OnSelectedItemChanged</code>, maybe I can use the answers in <a href="https://stackoverflow.com/questions/616948/how-to-get-treeviewitem-from-hierarchicaldatatemplate-item">this question</a> to get the <code>TreeViewItem</code> but I don't know how to get there. Does anyone know how and is it the right way to go?</p>