为什么在树视图 1 中,当我制作 CollapseAll 和 Expand 时,它并没有真正做到这一点?



当我运行程序时,我看到根节点

国家

然后,当我单击它时,我会看到"国家/地区"下的所有国家/地区节点但是我希望在运行程序时,它已经显示所有国家/地区节点,而无需单击国家/地区。

我在构造函数中尝试过:

PopulateTree(mainPath, treeView1.Nodes.Add("Countries"));
treeView1.CollapseAll();
treeView1.Nodes[0].Expand();

人口树

public void PopulateTree(string dir, TreeNode node)
        {
            DirectoryInfo directory = new DirectoryInfo(dir);
            foreach (DirectoryInfo d in directory.GetDirectories())
            {
                TreeNode t = new TreeNode(d.Name);
                PopulateTree(d.FullName, t);
                node.Nodes.Add(t);
            }
            foreach (FileInfo f in directory.GetFiles())
            {
                TreeNode t = new TreeNode(f.Name);
                node.Nodes.Add(t);
            }
        }

但它没有这样做,我在运行程序时仍然会看到国家/地区,要查看所有子节点,我需要单击国家/地区。

此行不起作用

treeView1.CollapseAll();
treeView1.Nodes[0].Expand();

TreeNode.Expand 仅向下扩展Nodes[0]到下一级节点。您应该使用 TreeNode.ExpandAll 展开"国家/地区"节点的所有子节点:

treeView1.Nodes[0].ExpandAll()

注意:您应该记住一件事。如果未为 TreeView 控件创建句柄,则此处正在处理诸如延迟折叠-扩展之类的操作。即每个节点都有expandOnRealizationcollapseOnRealization字段。当您尝试在创建树句柄之前扩展节点时,只需将expandOnRealization标志设置为 true。不会发送任何TVM_EXPAND Windows 消息来实际展开该节点。折叠也一样。当实现树节点时,执行以下代码:

// If node expansion was requested before the handle was created,
// we can expand it now.
if (expandOnRealization) {
    Expand();
}
// If node collapse was requested before the handle was created,
// we can expand it now.
if (collapseOnRealization) {
    Collapse();
}

因此,如果节点同时标记为折叠和扩展,那么它将首先展开,然后折叠。我相信这是你的情况。

相关内容

最新更新