question

Lettuce-3031 avatar image
0 Votes"
Lettuce-3031 asked ·

Datagrid not allowing sorting in UWP

Hi,

I'm using the UWP Datagrid control mentioned here: https://docs.microsoft.com/en-us/windows/communitytoolkit/controls/datagrid_guidance/datagrid_basics

And I'm trying to allow the user to be able to sort columns. I'm tried with CanUserSortColumns="True" on the grid and CanUserSort="True" on the columns. But nothing is happening when clicking the headers.

Looks like I can't enter xaml code here also?

windows-uwp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

PaulaMorgan-3461 avatar image
1 Vote"
PaulaMorgan-3461 answered ·

@Lettuce-3031

You also need to add code to the sorting event.

The documentation is here:
https://docs.microsoft.com/en-us/windows/communitytoolkit/controls/datagrid_guidance/group_sort_filter

Here's the sample code:

 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")
     {
         //Implement sort on the column "Range" using LINQ
         if (e.Column.SortDirection == null || e.Column.SortDirection == DataGridSortDirection.Descending)
         {
             dg.ItemsSource = new ObservableCollection(from item in _items
                                                                 orderby item.Range ascending
                                                                 select item);
             e.Column.SortDirection = DataGridSortDirection.Ascending;
         }
         else
         {
             dg.ItemsSource = new ObservableCollection(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;
         }
     }    
 }



· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.