通过 TreeViewItem 对象访问 WPF Treeview 选定索引 [英] Access WPF Treeview selected index through a TreeViewItem object

查看:20
本文介绍了通过 TreeViewItem 对象访问 WPF Treeview 选定索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有复选框的树视图,每个项目都使用 DataTemplate.

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>

在复选框单击事件中,我试图找出主树绑定列表中的选定索引.我得到的最接近的是在 CommandParameter 中传递 TreeViewItem 对象,但我不能用它做任何事情.我能够使用父项 ItemsControl:

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);

但是这里 s = -1.

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.

推荐答案

您正在获取的 ItemsControl 可能是 StackPanel 或 Grid.您应该能够通过事件发送者访问 Checkbox,并导航到 TreeViewItem 和 TreeView 并使用 IndexOf.

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());
 }

这篇关于通过 TreeViewItem 对象访问 WPF Treeview 选定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆