当我加载它时,我的树视图会崩溃,因此大约100×150像素.展开后,我希望树视图显示所有展开的节点.
为了做到这一点,随着树视图变大,表单需要变大,对吧?我是VB.net的新手,我试图在树视图中找到一个“GrowOnly”属性,但我找不到一个……有没有人做过这个?
最佳答案 处理AfterExpand / AfterCollapse事件
添加事件处理程序AfterExpand和AfterCollapse以使树视图对节点的展开/折叠作出反应.我为这个例子硬编码了填充,但实质上这只是用于调整表单大小的菜单,按钮等的高度.
Private Sub Rapports_tvAllReports_AfterExpand(sender As Object, e As System.Windows.Forms.TreeViewEventArgs) Handles Rapports_tvAllReports.AfterExpand, Rapports_tvAllReports.AfterCollapse
Dim Padding As Integer = 140 'Customize this, basically accounts for all buttons or menus included in the form which nests the treeview
Dim TreeViewHeight As Integer = GetOpenedNodesRecursively(Rapports_tvAllReports)
If formWindow = FormWindowState.Normal Then Me.Size = New Size(345, TreeViewHeight + Padding)
End Sub
我们所做的就是递增Y并将新Y设置为表单.为了使树视图与表单一起正确调整大小,将其锚定到顶部和底部.
递归地遍历节点
此函数将通过根节点并在打开的节点上调用递归函数.
Private Function GetOpenedNodesRecursively(ByVal aTreeView As TreeView)
Dim Y As Integer = 0
'Go through each node of the treeview (first level)
For Each n As TreeNode In aTreeView.Nodes
Y += Rapports_tvAllReports.ItemHeight
'If the user expands a node, recursively increment the Y
If n.IsExpanded Then Y += RecursiveYIncrement(n)
Next
Return Y
End Function
现在只需使用递归函数递增TreeViewHeight,该递归函数将返回在当前树视图中展开的所有节点的高度(Y).
Private Function RecursiveYIncrement(ByVal n As TreeNode)
Dim Y As Integer = 0
'Go through each node of the treeview (first level)
For Each aNode As TreeNode In n.Nodes
Y += Rapports_tvAllReports.ItemHeight
'If the user expands a node, recursively increment the Y
If aNode.IsExpanded Then Y += RecursiveYIncrement(aNode)
Next
Return Y
End Function
视觉再现
以下是我们完成后的样子:
我们从折叠的树视图开始
然后我们可以扩展一些节点,表单也会相应增长
然后我们可以重新折叠节点并扩展更多,表单再次调整!
请原谅我在屏幕截图中的法语,这是魁北克的常态……我们有义务这样做!