我有点挠头。
我正在使用winforms来构建业务应用程序,并且使用了很多ListViews。我有一个特定的列表,当填充项目时,可以根据项目的类型将项目的前景色属性设置为红色或黑色。我想对此进行排序,以便使用IComparer的自定义实现将所有红色项目都显示在列表顶部。它有效,但它反过来工作,因为所有红色项目都出现在底部。这是我的代码。
'//Populate list
For Each i In allStock.Where(Function(c) c.StockStatusID <> 6)
'//Add item, color in red if it is not contained within a certain date range
Next
'//Use my custom built IComparable implementing class(SortListByRedText) to sort items so that red items appear at the top.
Dim sorter As New SortListByRedText()
StockManagementList.ListViewItemSorter = sorter
StockManagementList.Sort()
'//Custom IComparer
Public Class SortListByRedText
Implements IComparer
Public Function Compare(x As Object, y As Object) As Integer Implements System.Collections.IComparer.Compare
Dim item1 = CType(x, ListViewItem)
Dim item2 = CType(y, ListViewItem)
If item1.ForeColor = Color.Red And item2.ForeColor = Color.Red Then
Return 0
ElseIf item1.ForeColor = Color.Red And item2.ForeColor = Color.Black Then
Return 1
ElseIf item1.ForeColor = Color.Black And item2.ForeColor = Color.Red Then
Return -1
Else
Return 0
End If
End Function
End Class
编辑:我已经在我的比较器中颠倒了 -1 和 1 顺序作为修复,但是当我不明白它为什么有效时,我不喜欢进行修复。当然,任何返回 -1 的东西都应该发送到列表的底部而不是顶部?
这是你去的方式。反转-1
并1
部分。
Public Function Compare(x As Object, y As Object) As Integer Implements System.Collections.IComparer.Compare
Dim item1 = CType(x, ListViewItem)
Dim item2 = CType(y, ListViewItem)
If item1.ForeColor = Color.Red And item2.ForeColor = Color.Red Then
Return 0
ElseIf item1.ForeColor = Color.Red And item2.ForeColor = Color.Black Then
Return -1
ElseIf item1.ForeColor = Color.Black And item2.ForeColor = Color.Red Then
Return 1
Else
Return 0
End If
End Function
另请注意,您忽略了黑色或红色以外的任何其他颜色。您可能需要考虑这一点。