【发布时间】:2015-08-29 19:19:27
【问题描述】:
我正在尝试在树视图组件上实现动态搜索,我几乎完成了它,除了因为它是基于文本框的 textchanged 事件的动态搜索,搜索字符串的第一个字符是总是找到,因此搜索功能会展开所有节点,因为它们是有效匹配。
问题是,随着搜索字符串变得更加完整,那些在匹配时展开的节点现在需要折叠,因为它们不再匹配搜索字符串......而这并没有发生......随着搜索字符串的变化,我还没有找到一种方法来动态折叠和展开节点......
我已经上传了一个视频和 Visual Studio 2012 解决方案,所以你可以看看它,看看我在哪里丢球...
这是我执行搜索的函数的代码:(您可以在视频中看到它按预期工作,所以我的问题是节点的扩展/折叠,因为它们匹配(或不匹配)搜索字符串。
我在“FindRecursive”函数中实现了一些想法来折叠和展开节点,但它没有按预期工作。由于我的逻辑错误,我什至设法将控件置于无限循环中。
任何帮助将不胜感激,
谢谢!
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
【问题讨论】:
-
因此,除了在“重置”新搜索时更改背景颜色之外,您还需要Collapse 节点。这样,只有匹配项会被扩展并使用新的搜索结果着色。目前您正在使用
CollapseAll()执行此操作,但仅当搜索框完全为空时。 -
Idle_Mind,感谢您的回复...我尝试在“FindRecursive”函数的开头添加一个 tviewToolIDs.CollapseAll()...它挂起应用程序..
-
您还需要在重置所有内容然后着色/展开匹配项时禁止重新绘制。您可以通过调用 BeginUpdate 执行所有更改,然后调用 EndUpdate 以允许它在新状态下重绘。
标签: vb.net search treeview collapse expand