2
votes

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. 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.

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).

So, is there any way to apply a custom sorting algorithm to a BindingListCollectionView object?

Thank you in advance.

EDIT:

Unfortunately, the solution has be placed in a DataGrid devided class, since the solution has to be generic.

Hope someone can help me.

1

1 Answers

1
votes

Make your property MyPropertyToSortOn of a custom type that implements IComparable, then add a sort descriptor to your listview:

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