1

我有一个树视图,它实现了 2 种类型的项目、文件夹和项目。当我对它们进行排序时,我希望这些项目出现在文件夹下方

喜欢

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
4

1 回答 1

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 属性。

于 2013-10-01T13:20:51.997 回答