2013-10-01 31 views
1

我有一個樹形視圖,實現了兩種類型的項目,文件夾和項目。 當我有點他們,我想要的物品出現在文件夾下面按結點類型按字母順序排列的.NET treeview排序

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 

回答

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其中第一排序標記屬性:

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屬性設置或沒有設置,則無錯誤檢查。

+0

是的,我使用'標籤'屬性噸這樣的東西。 tx這麼多,它會花費我很長時間才能找出這個簡單的解決方案 – aelgoa