简体   繁体   English

自定义排序算法到BindingListCollectionView

[英]Custom Sorting Algorithm to BindingListCollectionView

I am working on a WPF project which has some DataGrid 's, and in some of them I need to apply a custom sorting algorithm. 我正在一个WPF项目中,该项目具有一些DataGrid ,在其中一些中,我需要应用自定义排序算法。 So I have been searching a way to accomplish this and in many web pages I have found the following code: 因此,我一直在寻找一种方法来完成此任务,并且在许多网页中,我找到了以下代码:

var myListView = CollectionViewSource.GetDefaultView(myDataGrid.ItemsSource);

ListCollectionView myListCollectionView = myListView as ListCollectionView;

myListCollectionView.CustomSort = new CustomSorter();

.
.
.

public class CustomSorter : IComparer
{
    public int Compare(object x, object y)
    {
        // sorting logic ...
    }
}

That seems to be a very good method to carry out a custom sort, but my problem is that I cannot cast my variable myListView to ListCollectionView because it turned out to be a BindingListCollectionView object which besides lacks of functionality to set a custom sorting algorithm. 这似乎是执行自定义排序的一种非常好的方法,但是我的问题是我无法将变量myListViewListCollectionView因为它原来是BindingListCollectionView对象,除了缺乏设置自定义排序算法的功能外。

I found this solution but it does not work for me because they try to do the following: 我找到了解决方案,但对我不起作用,因为他们尝试执行以下操作:

ListCollectionView coll = new ListCollectionView(CollectionViewSource.GetDefaultView(myDataGrid.ItemsSource));

But there is no constructor that takes as a paremeter a ICollectionView object (which is what function GetDefaultView returns). 但是没有构造函数将ICollectionView对象作为参数(GetDefaultView返回的函数)。

So, is there any way to apply a custom sorting algorithm to a BindingListCollectionView object? 那么,有什么方法可以将自定义排序算法应用于BindingListCollectionView对象?

Thank you in advance. 先感谢您。

EDIT: 编辑:

Unfortunately, the solution has be placed in a DataGrid devided class, since the solution has to be generic. 不幸的是,由于该解决方案必须是通用的,因此该解决方案已放置在DataGrid划分的类中。

Hope someone can help me. 希望可以有人帮帮我。

Make your property MyPropertyToSortOn of a custom type that implements IComparable, then add a sort descriptor to your listview: 使您的属性MyPropertyToSortOn为实现IComparable的自定义类型,然后向您的列表视图添加排序描述符:

ListView.Items.SortDescriptions.Add(new SortDescription("MyPropertyToSortOn", ListSortDirection.Descending))


public class MyPropertyClass: IComparable{
  public int CompareTo(object obj) {
    //custom comparison implemented here, returns -1,0 or 1
  }
}

... ...

public class MyDataClass{
   public MyPropertyClass MyPropertyToSortOn {get;set;}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM