Question

I have a DataTable where all column datatypes are of a custom class called CellModel.

The table's defaultview is bound to a DataGrid, which autogenerates some templatecolumns where I setup DataTemplates and Bindings, and showing the data works perfect.

My issue is when i try to sort on the columns. I want to sort on a specific property within the custom class, but the default sorter won't recognize the custom class, so it invokes ToString() instead. By overriding and returning my property i'm able to sort, but it is PAINFULLY slow.

I've tried to implement a custom sorter on DataGrid.Sorting event like this:

private void DG_Sorting(object sender, DataGridSortingEventArgs e)
{
    var column = e.Column;
    e.Handled = true;
    var direction = (column.SortDirection != ListSortDirection.Ascending)
        ? ListSortDirection.Ascending
        : ListSortDirection.Descending;
    var lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(DG.ItemsSource);
    column.SortDirection = direction;
    lcv.CustomSort = new MyComparer();
    lcv.Refresh();
}

But GetDefaultView returns BindingListCollectionView which don't support CustomSorters..

I'm lost. How do I implement a custom comparer for sorting the data?

Was it helpful?

Solution

Found the issue. by using the lcv.SortDescriptions and implementing the IComparer interface on the CellModel class, i was able to use custom comparison. Also, the sorting speed was influenced since i had Virtualization disabled on the Datagrid. by enabling Virtualization, the sorting was faster.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top