UWP DataGrid排序

我们在winform中经常用到DataGridView,好像是自带排序功能的(点击对应列的表头会自动排序)。在UWP的DataGrid中不能自动排序,不过实现起来也不复杂,网上例程不多,但是我在微软MSDN上找到了非常详细的说明和例程。

1. DataGrid有一个自带的Sorting事件,在Xmal中为其添加对应的事件函数

<controls:DataGrid 
    x:Name="dg"
    Height="600" Margin="12"
    AutoGenerateColumns="False"
    CanUserSortColumns="True"
    Sorting="dg_Sorting">
        <controls:DataGrid.Columns>
            <controls:DataGridTextColumn Header="Range" Binding="{Binding Range}" Tag="Range"/>
            <!-- Add more columns -->
    </controls:DataGrid.Columns>
</controls:DataGrid>

2. 在对应事件函数中通过Linq排序数据源的对象(一般为对象的List),然后再重新绑定给DataGrid.

private void dg_Sorting(object sender, DataGridColumnEventArgs e)
{
    //Use the Tag property to pass the bound column name for the sorting implementation 
    if (e.Column.Tag.ToString() == "Range")
    {
        //Use the Tag property to pass the bound column name for the sorting implementation
        if (e.Column.Tag.ToString() == "Range")
        {
            //Implement sort on the column "Range" using LINQ
            if (e.Column.SortDirection == null || e.Column.SortDirection == DataGridSortDirection.Descending)
            {
                dg.ItemsSource = new ObservableCollection<Mountain>(from item in _items
                                                                    orderby item.Range ascending
                                                                    select item);
                e.Column.SortDirection = DataGridSortDirection.Ascending;
            }
            else
            {
                dg.ItemsSource = new ObservableCollection<Mountain>(from item in _items
                                                                    orderby item.Range descending
                                                                    select item);
                e.Column.SortDirection = DataGridSortDirection.Descending;
            }
        }
        // add code to handle sorting by other columns as required

        // Remove sorting indicators from other columns
        foreach (var dgColumn in dg.Columns)
        {
            if (dgColumn.Tag.ToString() != e.Column.Tag.ToString())
            {
                dgColumn.SortDirection = null;
            }
        }
    }
}

3. 其中dgColumn.SortDirection属性是用来设置表头的小箭头(代表正序或者倒序)

MSDN原文地址如下:

How to - Group, Sort and Filter data in the DataGrid Control - Windows Community Toolkit | Microsoft DocsGuidance document that shows how to group, sort and filter data in the DataGrid controlhttps://docs.microsoft.com/en-us/windows/communitytoolkit/controls/datagrid_guidance/group_sort_filter

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值