WPF 列表框集合自定义排序

WPF Listbox Collection custom sort

我有一个列表框

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

        }
    }

如何编写比较方法。我知道,它可以 return 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;
   }
}

这更符合您的问题

 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;
        }
    }

您只需要检查它是否以 "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());
}