如果要切换升序/降序,则还需要跟踪“排序顺序”。在您的比较器和您的列中单击事件处理程序。
例子:
ListViewItemComparer.vb:
Public Class ListViewItemComparer
...
Private col As Integer
Private order As SortOrder
...
Public Sub New()
col = 0
order = SortOrder.Ascending
...
Public Sub New(ByVal column As Integer, order As SortOrder)
...
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer
...
' Perform "compare": -1: s1 < s2; 0: s1=s2, 1: s1 > s2
Dim retval As Integer = -1
retval = [String].Compare(CType(x, ListViewItem).SubItems(col).Text, CType(y, ListViewItem).SubItems(col).Text)
' Reverse if "descending"
If order = SortOrder.Descending Then retval *= -1
Form1.vb
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
...
' Allow "reverse" sort
' Initial order is "NONE". As any column is clicked, the order will toggle between Ascending (first), then Descending
ReDim ColumnOrder(4)
For i As Integer = 0 To ColumnOrder.Length - 1
ColumnOrder(i) = SortOrder.Descending
Next
...
Private Sub ListView1_ColumnClick(sender As Object, e As ColumnClickEventArgs) Handles ListView1.ColumnClick
Dim ColumnHeader As System.Windows.Forms.ColumnHeader = ListView1.Columns(e.Column)
If ColumnOrder(e.Column) = SortOrder.Descending Then
ColumnOrder(e.Column) = SortOrder.Ascending
Else
ColumnOrder(e.Column) = SortOrder.Descending
End If
ListView1.Sorting = ColumnOrder(e.Column)
ListView1.Sort()
ListView1.ListViewItemSorter = New ListViewItemComparer(e.Column, ListView1.Sorting)
...
在此处查看更多详细信息:MSDN:使用 Windows 窗体按列对 ListView 项进行排序