【问题标题】:Access WPF Treeview selected index through a TreeViewItem object通过 TreeViewItem 对象访问 WPF Treeview 选定索引
【发布时间】:2010-11-15 23:52:37
【问题描述】:

我有一个使用 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:

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

但这里 s = -1。

我在复选框上也有标签,其中包含底层对象。当然,我可以在我的列表中查找对象,但似乎必须有一种更简单的方法来查找索引。

【问题讨论】:

    标签: wpf treeview


    【解决方案1】:

    您正在获取的 ItemsControl 可能是 StackPanel 或 Grid。您应该能够通过事件发送者访问 Checkbox,并向上导航到 TreeViewItem 和 TreeView 并使用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());
     }
    

    【讨论】:

    • 谢谢。 sp的父级是Grid,其父级为null。
    • 尝试使用 VisualTreeHelper.GetParent(grid)。
    • 返回 ContentPresenter - 如何从中获取 TreeViewItem?
    • 嗯,这有点乱了。我已经修改了答案。
    • 是的,也许看起来不太好,但可以:-) 感谢您的帮助。
    猜你喜欢
    • 2011-08-23
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    相关资源
    最近更新 更多