【问题标题】:Sorting DataTable bound to DataGrid with custom datatypes使用自定义数据类型对绑定到 DataGrid 的 DataTable 进行排序
【发布时间】:2013-12-22 14:22:21
【问题描述】:

我有一个 DataTable,其中所有列数据类型都是一个名为 CellModel 的自定义类。

表的默认视图绑定到 DataGrid,它会自动生成一些模板列,我在其中设置 DataTemplates 和 Bindings,并显示数据完美。

我的问题是当我尝试对列进行排序时。 我想对自定义类中的特定属性进行排序,但默认排序器无法识别自定义类,因此它调用 ToString() 代替。通过覆盖并返回我的属性,我可以进行排序,但它痛苦地很慢。

我尝试在 DataGrid.Sorting 事件上实现自定义排序器,如下所示:

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

但是 GetDefaultView 返回的 BindingListCollectionView 不支持 CustomSorters..

我迷路了。如何实现自定义比较器来对数据进行排序?

【问题讨论】:

    标签: sorting datagrid datatable dataview


    【解决方案1】:

    发现问题。通过使用 lcv.SortDescriptions 并在 CellModel 类上实现 IComparer 接口,我能够使用自定义比较。 此外,由于我在 Datagrid 上 禁用了虚拟化,因此排序速度也受到了影响。通过启用虚拟化,排序更快。

    【讨论】:

      猜你喜欢
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 2011-05-03
      • 2011-08-12
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      相关资源
      最近更新 更多