VB.Net - 如何在所有 TreeView 节点中动态搜索匹配(或不匹配)搜索字符串的展开和折叠节点中的字符串?

VB.Net - How to dynamicaly search for a string in all TreeView nodes expanding and collapsing nodes matching (or not) the search string?

我正在尝试在 treeview 组件上实现动态搜索,我几乎完成了它,除了因为它是基于文本框的 textchanged 事件的动态搜索,搜索的第一个字符始终会找到字符串,因此搜索函数会展开所有节点,因为它们是有效匹配项。

问题在于,随着搜索字符串变得更加完整,那些在匹配时展开的节点现在需要折叠,因为它们不再与搜索字符串匹配......而这并没有发生。 .. 我还找不到一种方法来随着搜索字符串的变化动态地折叠和展开节点...

我已经上传了一个视频和 Visual Studio 2012 年的解决方案,所以你可以看看它,看看我把球丢在哪里...

这是我执行搜索的函数的代码:(您可以在视频中看到它按预期工作,所以我的问题是节点的 expanding/collapsing,因为它们匹配(或不匹配)搜索字符串。

我在 "FindRecursive" 函数中实现了一些想法来折叠和展开节点,但它没有按预期工作。由于我的错误逻辑,我什至设法将控件置于无限循环中。

任何帮助将不胜感激,

谢谢!

Video showing the problem

Visual Studio 2012 Project + Test File

Private Sub txtFiltroIDs_TextChanged(sender As Object, e As EventArgs) Handles txtFilterToolIDs.TextChanged
        ClearBackColor()
        FindByText()
    End Sub

    Private Sub FindByText()
        Dim nodes As TreeNodeCollection = tviewToolIDs.Nodes
        Dim n As TreeNode
        For Each n In nodes
            FindRecursive(n)
        Next
    End Sub

    Private Sub FindRecursive(ByVal tNode As TreeNode)
        If txtFilterToolIDs.Text = "" Then
            tviewToolIDs.CollapseAll()
            tviewToolIDs.BackColor = Color.White
            ExpandToLevel(tviewToolIDs.Nodes, 1)
        Else
            Dim tn As TreeNode
            For Each tn In tNode.Nodes
                ' if the text properties match, color the item
                If tn.Text.Contains(txtFilterToolIDs.Text) Then
                    tn.BackColor = Color.Yellow
                    tn.EnsureVisible()        'Scroll the control to the item
                End If

                FindRecursive(tn)
            Next
        End If
    End Sub

    Private Sub ClearBackColor()
        Dim nodes As TreeNodeCollection
        nodes = tviewToolIDs.Nodes
        Dim n As TreeNode
        For Each n In nodes
            ClearRecursive(n)
        Next
    End Sub

    Private Sub ClearRecursive(ByVal treeNode As TreeNode)
        Dim tn As TreeNode
        For Each tn In treeNode.Nodes
            tn.BackColor = Color.White
            ClearRecursive(tn)
        Next
    End Sub

根据我最初的评论,尝试类似的操作:

Private Sub txtFiltroIDs_TextChanged(sender As Object, e As EventArgs) Handles txtFilterToolIDs.TextChanged
    tviewToolIDs.BeginUpdate()
    tviewToolIDs.CollapseAll()
    ClearBackColor()
    FindByText()
    tviewToolIDs.EndUpdate()
    tviewToolIDs.Refresh()
End Sub