0
votes

I have a treeview with checkboxes for each item using a DataTemplate.

<TreeView ItemsSource="{Binding}">
<DataTemplate DataType="{x:Type local:MatchDataLeaf}">
    <Grid Margin="3">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="240"/>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="150"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="60"/>
        </Grid.ColumnDefinitions>

        <StackPanel Grid.Column="0" Orientation="Horizontal">
            <CheckBox x:Name="selectCheckBtn" Grid.Column="0" IsChecked="True" Click="select_Click"
                      Tag="{Binding}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}"/>
            <TextBlock Grid.Column="1" Margin="5,0,0,0" Text="{Binding Path=Name}" FontFamily="Arial" FontSize="12" FontWeight="Bold" Foreground="Black" VerticalAlignment="Center"/>
    </StackPanel>
 </Grid>
</DataTemplate>

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:

ItemsControl parent = ItemsControl.ItemsControlFromItemContainer(selectedItem);
int s = parent.Items.IndexOf(selectedItem);

But s = -1 here.

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.

1

1 Answers

0
votes

The ItemsControl you are fetching might be the StackPanel, or the Grid. You should be able to access the Checkbox through the event sender, and navigate up to the TreeViewItem and TreeView and use IndexOf.

 private void CheckBox_Click(object sender, RoutedEventArgs e)
 {
        CheckBox cb = (CheckBox)sender;
        StackPanel sp = (StackPanel)cb.Parent;
        Grid g = (Grid)sp.Parent;
        ContentPresenter cp = (ContentPresenter)VisualTreeHelper.GetParent(g);
        IList l = (IList)myTreeView.ItemsSource;
        object o = cp.Content;
        MessageBox.Show(l.IndexOf(o).ToString());
 }