初始DataGrid排序 [英] Initial DataGrid Sorting

查看:122
本文介绍了初始DataGrid排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件,其中包含WPF工具包 DataGrid 。我的应用程序中的许多不同地方都使用了此控件。网格不知道将显示的数据类型。有没有一种方法可以不管网格填充了什么数据,都按照第一列的升序对网格进行初始排序?我不认为可以使用 CollectionViewSource ,因为我不知道绑定到该属性的 PropertyName 第一栏。

I have a user control that contains a WPF toolkit DataGrid. This control is used in many different places in my app. The grid has no knowledge as to the type of data that will show. Is there a way to initially sort the grid by the first column in ascending order no matter what data the grid is populated with? I don't think I can use a CollectionViewSource because I don't know the PropertyName of the property bound to the first column.

推荐答案

您可以关联到一个事件:

You could hook to an event:

dataGrid.AutoGeneratedColumns += dataGrid_AutoGeneratedColumns;

并对第一列进行排序:

void dataGrid_AutoGeneratedColumns(object sender, EventArgs e)
{
    var firstCol = dataGrid.Columns.First();
    firstCol.SortDirection = ListSortDirection.Ascending;
    dataGrid.Items.SortDescriptions.Add(new SortDescription(firstCol.SortMemberPath, ListSortDirection.Ascending));
}

我建议您创建一个派生的单独的 DataGrid 控件,将其放置在此处并使用新控件避免每次都重复代码。

I would suggest you to create a derived separate DataGrid control, placing this logic there and using the new control to avoid repeating the code every time.

public class CustomDataGrid : DataGrid
{
    public DynamicDataGrid()
    { ... }

    ...
}

这篇关于初始DataGrid排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆