在VB.Net中,根据文件路径导航到Treeview节点

问题描述 投票:0回答:1
在我的 Windows 资源管理器类型应用程序中,具有必需的树视图和列表视图,并且用户选择的文件路径在文本框中不断更新,是否有一种方法可以直接使用实际文件路径导航到树视图中的不同节点?每个节点的Text和Tag都是相同的。例如,这对于复制资源管理器的“向上”按钮等很有用,但除了冗长的循环过程之外,我似乎找不到任何关于它的信息。 任何建议将不胜感激。

vb.net listview treeview
1个回答
0
投票

Find

中有一个
TreeNodeCollection
方法。它返回与节点的 
Name
 属性匹配的找到节点的数组。

我在表单设计器中设置了一个小测试表单(插入 Form1.Designer.vb):

Private Sub InitializeComponent() Dim TreeNode1 As TreeNode = New TreeNode("Private") Dim TreeNode2 As TreeNode = New TreeNode("Public") Dim TreeNode3 As TreeNode = New TreeNode("Data", New TreeNode() {TreeNode1, TreeNode2}) Dim TreeNode4 As TreeNode = New TreeNode("Pictures") Dim TreeNode5 As TreeNode = New TreeNode("C:", New TreeNode() {TreeNode3, TreeNode4}) TreeView1 = New TreeView() TextBox1 = New TextBox() SuspendLayout() ' ' TreeView1 ' TreeView1.HideSelection = False TreeView1.Location = New Point(55, 213) TreeView1.Name = "TreeView1" TreeNode1.Name = "C:\Data\Private" TreeNode1.Text = "Private" TreeNode2.Name = "C:\Data\Public" TreeNode2.Text = "Public" TreeNode3.Name = "C:\Data" TreeNode3.Text = "Data" TreeNode4.Name = "C:\Pictures" TreeNode4.Text = "Pictures" TreeNode5.Name = "C:" TreeNode5.Text = "C:" TreeView1.Nodes.AddRange(New TreeNode() {TreeNode5}) TreeView1.Size = New Size(262, 144) TreeView1.TabIndex = 3 ' ' TextBox1 ' TextBox1.Location = New Point(55, 364) TextBox1.Name = "TextBox1" TextBox1.Size = New Size(262, 23) TextBox1.TabIndex = 4 ' ' Form1 ' AutoScaleDimensions = New SizeF(7F, 15F) AutoScaleMode = AutoScaleMode.Font ClientSize = New Size(800, 450) Controls.Add(TextBox1) Controls.Add(TreeView1) Name = "Form1" Text = "Form1" ResumeLayout(False) PerformLayout() End Sub Friend WithEvents TreeView1 As TreeView Friend WithEvents TextBox1 As TextBox
然后我添加了这个 TextChanged 事件处理程序:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged Dim nodes As TreeNode() = TreeView1.Nodes.Find(TextBox1.Text, True) If nodes.Length > 0 Then Dim selectedNode As TreeNode = nodes(0) TreeView1.SelectedNode = selectedNode selectedNode.Expand() selectedNode.EnsureVisible() End If End Sub
现在,当我输入路径时,所选节点会不断更新。请注意,节点的名称是到目前为止的整个路径,而显示的文本只是路径的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.