如何遍历 TreeView 元素?

How to iterate through TreeView elements?

我几乎到处都在寻找答案,但找不到有效的答案..

我来自 VBA 深厚的背景,所以我非常了解语法,但我仍然不了解 WPF 应用程序在 NET 6.0 中的工作方式,哈哈。

情况如下:

我的应用程序中有一个 TreeView 元素 Window,它有两个父项和一个子项。

我的 VBA 大脑逻辑会这样说

x = 0
Do While x < TreeViewObject.Items(x).Count ' This would be the iteration for finding out parents
y = 0

Do While y < TreeViewObject.Items(x).Children.Count ' This would be the iteration for finding out how many children the parents have.

Msgbox(TreeViewObject.Items(x).Children(y)) ' prints out the children's values

y = y + 1
Loop

x = x + 1
Loop

..会工作,但这里的逻辑比我预期的要糟糕得多,我如何遍历 TreeView 元素?

这演示了如何使用递归遍历 Treeview

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    IterateTV(TreeView1.Nodes(0))
End Sub

Private Sub IterateTV(nd As TreeNode)
    Debug.Write("' ")
    Debug.WriteLine(nd.Text)
    For Each tnd As TreeNode In nd.Nodes
        IterateTV(tnd)
    Next
End Sub
'TreeView1
' root
'   A
'   B
'       B sub 1
'       B sub 2
'           B sub 2 sub a
'       B sub 3
'   C

不管我的老 post,这个实现是完全优越的:

        For Each VarParent In CategoryList.Items
            MsgBox(VarParent.ToString)

            For Each VarChild In VarParent.Items
                MsgBox(VarChild.ToString)
            Next

        Next

此方法将遍历每个父项,然后是它拥有的每个子项,其逻辑类似于您在 VBA 中找到的内容,但有 0 个额外的复杂性。

旧代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    IterateTV(CategoryList)
End Sub

Private Sub IterateTV(nd)
    For Each tnd In nd.Items
        IterateTV(tnd)
        MsgBox(tnd.ToString)
    Next
End Sub