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()

そして、Tag プロパティを最初にソートする更新された Comparer:

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 に答える