title: Access WPF Treeview selected index through a TreeViewItem object
body: <p>I have a treeview with checkboxes for each item using a DataTemplate.</p>
  
  <pre><code>&lt;TreeView ItemsSource="{Binding}"&gt;
  &lt;DataTemplate DataType="{x:Type local:MatchDataLeaf}"&gt;
      &lt;Grid Margin="3"&gt;
          &lt;Grid.ColumnDefinitions&gt;
              &lt;ColumnDefinition Width="240"/&gt;
              &lt;ColumnDefinition Width="100"/&gt;
              &lt;ColumnDefinition Width="150"/&gt;
              &lt;ColumnDefinition Width="*"/&gt;
              &lt;ColumnDefinition Width="60"/&gt;
          &lt;/Grid.ColumnDefinitions&gt;
  
          &lt;StackPanel Grid.Column="0" Orientation="Horizontal"&gt;
              &lt;CheckBox x:Name="selectCheckBtn" Grid.Column="0" IsChecked="True" Click="select_Click"
                        Tag="{Binding}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}"/&gt;
              &lt;TextBlock Grid.Column="1" Margin="5,0,0,0" Text="{Binding Path=Name}" FontFamily="Arial" FontSize="12" FontWeight="Bold" Foreground="Black" VerticalAlignment="Center"/&gt;
      &lt;/StackPanel&gt;
   &lt;/Grid&gt;
  &lt;/DataTemplate&gt;
  </code></pre>
  
  <p></p>
  
  <p>In the checkbox click event, I'm trying to figure out the selected index in the main tree's binded list. The closest I got is passing the TreeViewItem object along in the CommandParameter, but I can't do anything with it. I was able to the the parent ItemsControl using:</p>
  
  <pre><code>ItemsControl parent = ItemsControl.ItemsControlFromItemContainer(selectedItem);
  int s = parent.Items.IndexOf(selectedItem);
  </code></pre>
  
  <p>But s = -1 here.</p>
  
  <p>I also have the Tag on the checkbox that has the underlying object in it. Sure, I can do a Find on my list for the object, but it just seems like there must be a simpler way to find the index.</p>