我正在摸不着头脑。
我正在使用winforms构建业务应用程序,而且我使用了大量的ListView。我有一个特定的列表,当填充项目时,可以将项目的forecolor属性设置为红色或黑色,具体取决于项目的类型。我想对此进行排序,以便使用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的任何内容都应该发送到列表的底部而不是顶部?
答案 0 :(得分: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
另请注意,您忽略了除黑色或红色以外的任何其他颜色。您可能需要考虑这一点。