C# 展开/关闭用户控件树

C# 展开/关闭用户控件树,c#,winforms,tree,treeview,C#,Winforms,Tree,Treeview,下面的代码用于在用户控件中加载树视图的xml文件。不知何故,我觉得扩展/关闭的代码没有很好地编码。有没有其他更干净的编码方式 try{ this.tvTraceSelect.Progress = true; this.tvTraceSelect.UnitsPath = unitsPath; this.tvTraceSelect.TracesPath = tracesPath; this.tvTraceSelect.View = Traces.View.Files;

下面的代码用于在用户控件中加载树视图的xml文件。不知何故,我觉得扩展/关闭的代码没有很好地编码。有没有其他更干净的编码方式

try{
    this.tvTraceSelect.Progress = true;
    this.tvTraceSelect.UnitsPath = unitsPath;
    this.tvTraceSelect.TracesPath = tracesPath;
    this.tvTraceSelect.View = Traces.View.Files;
    this.tvTraceSelect.TreeView.CollapseAll();
    if (this.tvTraceSelect.TreeView.Nodes.Count > 0)
    {
        this.tvTraceSelect.TreeView.Nodes[0].Expand();
        if (this.tvTraceSelect.TreeView.Nodes[0].Nodes.Count > 0)
        {
            this.tvTraceSelect.TreeView.Nodes[0].Nodes[0].Expand();
            if (this.tvTraceSelect.TreeView.Nodes[0].Nodes[0].Nodes.Count > 0)
            {
                this.tvTraceSelect.TreeView.Nodes[0].Nodes[0].Nodes[0].Expand();
                if (this.tvTraceSelect.TreeView.Nodes[0].Nodes[0].Nodes[0].Nodes.Count > 0)
                {
                    this.tvTraceSelect.TreeView.Nodes[0].Nodes[0].Nodes[0].Nodes[0].Expand();
                }
            }
        }
    }
}catch (Exception _excep)
{
    MessageBox.Show(this, "An error occured during the initialization of the InitTracesView .\nDetails: " 
            + _excep.Message + "\n\n" + _excep.StackTrace, "Initialization error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
可以这样称呼:

ExpandFirst(this.tvTraceSelect.TreeView.Nodes)
可以这样称呼:

ExpandFirst(this.tvTraceSelect.TreeView.Nodes)


你考虑过使用递归吗?@Charlie Kilian:你能给我一些解决方案吗?首先让我问一下,你想实现什么?看起来您想要展开树中的所有节点。这就是你想要的吗?@Charlie Kilian:Sam给出了正确的答案,谢谢你考虑过使用递归吗?@Charlie Kilian:你能给我一些解决方案吗?首先让我问一下,你想实现什么?看起来您想要展开树中的所有节点。这就是你想要的吗?@Charlie Kilian:Sam给出了正确的答案,谢谢你:我只想在选择过程中简化我的代码……因为它工作得很好。:你的代码在我加载时会展开所有树。这不利于用户看到自动展开。您只希望看到每个级别的第一个子节点展开?此代码不正确,它只展开第一个节点。改用foreach。使用ExpandAll()是更好的方法。@HansPassant-我同意如果目标是扩展所有节点,那么ExpandAll()将是更好的方法。然而,OP发布了一条评论(该评论已被删除),表示他们不希望整个树被扩展。他们只是想重现代码现在正在做的事情,这似乎只是在每个级别上扩展第一个子级。因此,为什么我的方法被称为ExpandFirst,而不是ExpandAll…:我只想在选择过程中简化我的代码…因为它工作得很好。:您的代码在加载它时会展开所有树。这不利于用户看到自动展开。您只希望看到每个级别的第一个子节点展开?此代码不正确,它只展开第一个节点。改用foreach。使用ExpandAll()是更好的方法。@HansPassant-我同意如果目标是扩展所有节点,那么ExpandAll()将是更好的方法。然而,OP发布了一条评论(该评论已被删除),表示他们不希望整个树被扩展。他们只是想重现代码现在正在做的事情,这似乎只是在每个级别上扩展第一个子级。因此,我的方法称为ExpandFirst,而不是ExpandAll。。。