本文介绍了如何从代码中选择 TreeView 项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个三级树视图.如何从代码中选择第三级的任何项目?我尝试了许多博客和 stackoverflow 上提到的方法,但它似乎只适用于第一级(dbObject 对于第一级以下的项目为 null).

I have a three level treeview. How do I select any item in third level from code? I tried a method mentioned in many blogs and on stackoverflow but it seems to work only for first level (dbObject is null for items on below first level).

这是我用来选择 TreeViewItem 的代码.我错过了什么吗?

Here is the code I'm using to select TreeViewItem. Do I miss something?

public static void SetSelectedItem(this TreeView control, object item)
{
    try
    {
        var dObject = control.ItemContainerGenerator.ContainerFromItem(item);

        //uncomment the following line if UI updates are unnecessary
        ((TreeViewItem)dObject).IsSelected = true;

        MethodInfo selectMethod = typeof(TreeViewItem).GetMethod("Select",
            BindingFlags.NonPublic | BindingFlags.Instance);

        selectMethod.Invoke(dObject, new object[] { true });
    }
    catch { }
}

推荐答案

另一种选择是使用绑定.如果您有一个对象使用绑定来获取每个 TreeViewItem 的文本(例如),您可以创建一个也绑定 IsSelected 属性的样式:

Another option would be to use binding. If you have an object that you are using binding with to get the text of each TreeViewItem (for example), you can create a style that also binds the IsSelected property:

<TreeView>
    <TreeView.Resources>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsSelected"
                    Value="{Binding Path=IsSelected, Mode=TwoWay}" />
        </Style>
    </TreeView.Resources>
</TreeView>

这假设绑定对象具有 bool 类型的 IsSelected 属性.然后,您可以通过将 IsSelected 设置为 true 为其相应对象来选择 TreeViewItem.

This assumes that the bound object has an IsSelected property of type bool. You can then select a TreeViewItem by setting IsSelected to true for its corresponding object.

同样的方法可以与 IsExpanded 属性一起使用,以控制 TreeViewItem 何时展开或折叠.

The same approach can be used with the IsExpanded property to control when a TreeViewItem is expanded or collapsed.

这篇关于如何从代码中选择 TreeView 项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 11:50