Pre-sorting a DataGrid in WPF

后端 未结 5 1919
野性不改
野性不改 2020-12-06 04:15

I have a DataGrid in WPF app with several columns, including a Name column. If the users switches to a particular view, I want the data to be pre-sorted by Name

5条回答
  •  囚心锁ツ
    2020-12-06 04:54

    This works for me.

    ListSortDirection sortDirection;
    int selectedColumnIndex;
    private void customerDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
    {
        selectedColumnIndex = e.Column.DisplayIndex;
        sortDirection = (e.Column.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending: ListSortDirection.Ascending);
    }
    
    private void applySortDescriptions(ListSortDirection listSortDirection)
    {
        //Clear current sort descriptions 
        customerDataGrid.Items.SortDescriptions.Clear();
    
        //Get property name to apply sort based on desired column 
        string propertyName = customerDataGrid.Columns[selectedColumnIndex].SortMemberPath;
    
        //Add the new sort description 
        customerDataGrid.Items.SortDescriptions.Add(new SortDescription(propertyName, listSortDirection));
    
        //apply sort 
        applySortDirection(listSortDirection);
    
        //refresh items to display sort 
        customerDataGrid.Items.Refresh();
    }
    
    private void applySortDirection(ListSortDirection listSortDirection)
    {
        customerDataGrid.Columns[selectedColumnIndex].SortDirection = listSortDirection;
    }
    

提交回复
热议问题