简体   繁体   English

排序数据网格

[英]Sorting a DataGrid

The order of rows in my DataGrid does not change as it should when I click on a column header. 单击列标题时,DataGrid中的行顺序不会更改,因为它应该更改。 I've implemented a custom sorter and this is the prototype of my Compare-Function, which is successfully being called: 我实现了一个自定义排序器,这是我的Compare-Function的原型,该原型被成功称为:

    public int Compare(object x, object y)
    {
        var rowView1 = x as DataRowView;
        var rowView2 = y as DataRowView;
        var row1 = rowView1.Row;
        var row2 = rowView2.Row;
        var row1Id = Convert.ToInt32(row1[0]);
        var row2Id = Convert.ToInt32(row2[0]);

        if (SortDirection == ListSortDirection.Ascending)
        {
            return row1Id.CompareTo(row2Id);
        }
        else
        {
            return row2Id.CompareTo(row1Id);
        }
    }

The compare function above seems to work as suggested, it simply compares Ids and in debug mode, I see that the comparisons lead to valid returns ( +1 or -1). 上面的compare函数似乎按建议的方式工作,它只是比较Ids,并且在调试模式下,我发现比较会导致有效的返回值(+1或-1)。 Hower, the order of elements in the datagrid does not change. 但是,数据网格中元素的顺序不会改变。 What am I missing out here? 我在这里错过了什么? I've googled for so long that I'm close to needing glasses.. thanks for any help! 我已经搜索了很长时间,以至于我几乎要戴眼镜了。谢谢您的帮助!

EDIT: the xaml for my grid 编辑:我的网格的XAML

<DataGrid result:CustomSortBehaviour.AllowCustomSort="True" 
          Name="ResultDataGrid"
          IsReadOnly="True"
          ItemsSource="{Binding ResultDataTable}">
</DataGrid>

The property you actually need to set is CanUserSortColumns 您实际需要设置的属性是CanUserSortColumns

So set that to true and then if that doesn't work do this. 因此,将其设置为true,然后如果不起作用,请执行此操作。

<DataGrid Sorting="OnDataGridSort"
          CanUserSortColumns="True" 
          Name="ResultDataGrid"
          IsReadOnly="True"
          ItemsSource="{Binding ResultDataTable}">
</DataGrid>

And then all you need to give the ListcollectionView an instance of your comparer. 然后,您需要为ListcollectionView提供一个比较器的实例。

void OnDataGridSort(object sender, System.Windows.Controls.DataGridSortingEventArgs e)
{
    DataGrid dg = sender as DataGrid;
    ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg.ItemsSource);
    lcv.CustomSort = [Your IComparer instance here];
    e.Handled;
}

您是否设置了DataGrid.AllowSorting属性?

Add this to your code 将此添加到您的代码

allowsorting="true" allowsorting = “真”

You can Use This. 您可以使用它。

<DataGrid  allowsorting="true" result:CustomSortBehaviour.AllowCustomSort="True" Name="ResultDataGrid" IsReadOnly="True" ItemsSource="{Binding ResultDataTable}">
    </DataGrid>

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

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