如何遍历TreeView元素



我在这里到处找答案,但找不到有效的答案。。

我来自一个VBA密集的背景,所以我很理解语法,但我仍然不明白WPF应用程序是如何在NET 6.0中工作的,哈哈。

情况如下:

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

我的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

抛开我以前的帖子不谈,这个实现是完全优越的:

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

此方法将遍历每个父对象,然后遍历它所具有的每个子对象,其逻辑与VBA中的逻辑类似,但没有额外的复杂性。

旧代码:

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

最新更新