我有一个树视图,它实现了两种类型的项目,文件夹和项目。 当我对它们进行排序时,我希望项目显示在文件夹
下面像
folder a
subfolder a
subitem z
folder b
item a
item b
如何修改排序例程?
Public Class ascsorter
Implements Collections.IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) _
As Integer Implements Collections.IComparer.Compare
Dim tx As Windows.Forms.TreeNode = CType(x, Windows.Forms.TreeNode)
Dim ty As Windows.Forms.TreeNode = CType(y, Windows.Forms.TreeNode)
Return -String.Compare(tx.Text, ty.Text)
End Function
End Class
Public Class descsorter
Implements Collections.IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) _
As Integer Implements Collections.IComparer.Compare
Dim tx As Windows.Forms.TreeNode = CType(x, Windows.Forms.TreeNode)
Dim ty As Windows.Forms.TreeNode = CType(y, Windows.Forms.TreeNode)
Return String.Compare(tx.Text, ty.Text)
End Function
End Class
答案 0 :(得分:1)
您需要能够区分哪些节点是文件夹以及哪些节点是项目。 Tag
属性可用于此目的。在这个例子中,我使用“a”表示文件夹,“b”表示项目:
使用标记:
对未分类的节点进行示例Dim nodeA As New TreeNode("folder a") With {.Tag = "a"}
nodeA.Nodes.Add(New TreeNode("subitem z") With {.Tag = "b"})
nodeA.Nodes.Add(New TreeNode("subfolder a") With {.Tag = "a"})
nodeA.ExpandAll()
TreeView1.Nodes.Add(New TreeNode("folder b") With {.Tag = "a"})
TreeView1.Nodes.Add(nodeA)
TreeView1.Nodes.Add(New TreeNode("item b") With {.Tag = "b"})
TreeView1.Nodes.Add(New TreeNode("item a") With {.Tag = "b"})
TreeView1.TreeViewNodeSorter = New ascsorter
TreeView1.Sort()
更新的Comparer首先对Tag属性进行排序:
Public Class ascsorter
Implements Collections.IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) _
As Integer Implements Collections.IComparer.Compare
Dim tx As Windows.Forms.TreeNode = CType(x, Windows.Forms.TreeNode)
Dim ty As Windows.Forms.TreeNode = CType(y, Windows.Forms.TreeNode)
If Not tx.Tag.Equals(ty.Tag) Then
Return String.Compare(tx.Tag, ty.Tag)
End If
Return String.Compare(tx.Text, ty.Text)
End Function
End Class
注意:如果设置了Tag属性,则不会检查错误。