Initial DataGrid Sorting

北城以北 提交于 2019-12-24 02:58:04

问题


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.


回答1:


You could hook to an event:

dataGrid.AutoGeneratedColumns += dataGrid_AutoGeneratedColumns;

and sort the first column:

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

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()
    { ... }

    ...
}


来源:https://stackoverflow.com/questions/8944822/initial-datagrid-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!