WPF Listbox Collection自定义排序

时间:2015-06-22 14:40:26

标签: wpf sorting listbox compare collectionview

我有一个列表框

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。我如何设置优先级。

2 个答案:

答案 0 :(得分:2)

您只需检查它是否以" price"。

开头

请注意,我不认为ToString()是合适的;您应该实施IComparer<T>并在列表框中强烈输入您的对象。

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)

以下是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;
   }
}

这更具体针对您的问题

 internal class PrioritySorting : IComparer
    {
        private string _text;
        public PrioritySorting(string text)
        {
            _text = text;
        }

        public int Compare(object x, object y)
        {
            var str1 = x as string;
            var str2 = y as string;

            if (str1.StartsWith("price") )
            {
                if (str2.StartsWith("price"))
                    return 0;
                return 1;
            }

            return -1;
        }
    }