WPF列表框集合自定义排序
我有一个列表框WPF列表框集合自定义排序,wpf,sorting,listbox,compare,collectionview,Wpf,Sorting,Listbox,Compare,Collectionview,我有一个列表框 DropPrice MyPrice Price1 Price2 我想这样分类 Price1 Price2 DropPrice MyPrice 我的意思是,如果有一个项目以序列“price”开头,它将获得优先级,否则最小的字符串将获得优先级 我的源代码: var lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(_itemsSource)); var customSort = new PriorityS
DropPrice
MyPrice
Price1
Price2
我想这样分类
Price1
Price2
DropPrice
MyPrice
我的意思是,如果有一个项目以序列“price”开头,它将获得优先级,否则最小的字符串将获得优先级
我的源代码:
var lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(_itemsSource));
var customSort = new PrioritySorting("price");
lcv.CustomSort = customSort;
internal class PrioritySorting : IComparer
{
private string _text;
public PrioritySorting(string text)
{
_text = text;
}
public int Compare(object x, object y)
{
//my sorting code here
}
}
如何编写比较方法。我知道,它可以返回1,0或-1。如何设置优先级。以下是IComparer的示例代码片段
private class sortYearAscendingHelper : IComparer
{
int IComparer.Compare(object a, object b)
{
car c1=(car)a;
car c2=(car)b;
if (c1.year > c2.year)
return 1;
if (c1.year < c2.year)
return -1;
else
return 0;
}
}
你只需要检查它是否以“价格”开头 请注意,我认为
ToString()
不合适;您应该实现IComparer
,并在列表框中强烈键入对象
public int Compare(object x, object y)
{
// test for equality
if (x.ToString() == y.ToString())
{
return 0;
}
// if x is "price" but not y, x goes above
if (x.ToString().StartsWith("Price") && !y.ToString().StartsWith("Price"))
{
return -1;
}
// if y is "price" but not x, y goes above
if (!x.ToString().StartsWith("Price") && y.ToString().StartsWith("Price"))
{
return 1;
}
// otherwise, compare normally (this way PriceXXX are also compared among themselves)
return string.Compare(x.ToString(), y.ToString());
}
我知道,但如果有一个项目以给定的顺序开始,我需要先显示该项目,这是不对的。。。这样,您只需将以“价格”开头的项目与不以“价格”开头的项目分开。他希望他们也被分类。这意味着,如果两个项目都以“价格”开头,或者两者都不以“价格”开头,您应该正常地比较它们并返回比较结果。看起来很有效,但我们需要交换1和-1位置。我不太确定哪一个会去哪里。。。修正了,谢谢。另外,我们不能检查字符串>字符串(x>y),如果我们使用字符串会怎么样。比较(x,y)当然可以。但正如我所说,我认为使用ToString()不是一个好主意(我甚至不确定它是否适用于您的对象)。您应该强式键入列表项,并使用这些项的属性进行比较。
public int Compare(object x, object y)
{
// test for equality
if (x.ToString() == y.ToString())
{
return 0;
}
// if x is "price" but not y, x goes above
if (x.ToString().StartsWith("Price") && !y.ToString().StartsWith("Price"))
{
return -1;
}
// if y is "price" but not x, y goes above
if (!x.ToString().StartsWith("Price") && y.ToString().StartsWith("Price"))
{
return 1;
}
// otherwise, compare normally (this way PriceXXX are also compared among themselves)
return string.Compare(x.ToString(), y.ToString());
}