UWP ObservableCollection multi column sorting

BitSmithy 1,771 Reputation points
2021-10-25T20:25:05.957+00:00

Hello,

I found a documentation How to sort UWP DataGrid
https://learn.microsoft.com/en-us/windows/communitytoolkit/controls/datagrid_guidance/group_sort_filter

But how to do multicolumn sorting. For example there are four columns k0, k1, k2, k3
I want to sort DataGrid to sort by these columns
k0 ascending
k1 ascending
k2 descending
k3 descending

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Roy Li - MSFT 32,111 Reputation points Microsoft Vendor
    2021-10-26T03:25:55.857+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Update:

    For such a requirement, you could achieve the data result using ObservableCollection like what you've seen in the Group, sort and filter data in the DataGrid Control

    Here is the code:

       MyListView.ItemsSource = new ObservableCollection<TestClass>(from item in source  
                                                                             orderby item.A ascending, item.B descending  
                                                                             select item);  
            }  
    

    The source you get using this code is sorted by A ascending, and B descending when A is the same.

    This is what the result looks like:

    143774-image.png

    That you need to do else is to complete the DataGrid logic and use the correct sorting code in code-behind.

    -----------------------------------------------------------------------------------------------------------------------------

    I want to sort DataGrid to sort by these columns

    I have to say No. Generally, one row represents one data object in the ObservableCollection. The values displayed in K0, k1 are just properties of that data object. These properties cannot be divided into individual data objects. So only one rule could be applied to these data at the same time.

    143608-image.png

    For example, as you could see in the image, this is what it looks like when sorting these data objects on K1 - ascending( We call it Rule 1). But if you want to sort the data on k3 - descending at the same time(We call it Rule 2), The two data will conflict. Data BitSmithy should place in the 2nd in Rule 2 but it actually places in the 1st in Rule 1. Data BitSmithy is a whole object, we can't just move the K3 data because it's just a property of Data BitSmithy.

    If you still have questions about this. please feel free to contact us.

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful