Home > Software engineering >  Correct way to sort GridView or its backing ObservableCollection?
Correct way to sort GridView or its backing ObservableCollection?

Time:12-11

I've been writing a hobby project in WinUI 3 recently and have run into some trouble.

In my app, I have a GridView that's bound in XAML to an ObservableCollection, as recommended in the WinUI documentation. This works great, but now I need to be able to sort and filter the items in the GridView and it's unclear what the most "correct" or idiomatic way of going about this is.

Googling reveals that WPF has some bits in CollectionViewSource to handle this, but those appear to have been removed in WinUI.

Currently the only thing I've founded that works is to remove the XAML binding, change the ObservableCollection to a List, and then when the user sorts, manually set the GridView's source to null followed by setting the source to a sorted version of the List. If I'm not mistaken this breaks virtualization in the GridView though, so it doesn't seem like what I'm supposed to be doing.

I would greatly appreciate any insight on this.

CodePudding user response:

In WinUI, you are supposed to sort the source collection, i.e. the ObservableCollection<T>, yourself.

This is a modified (and fairly untested) BubbleSort method from here that should come in handy:

public static class ObservableCollectionExtensions
{
    public static void BubbleSort<T>(this ObservableCollection<T> o) where T : IComparable
    {
        for (int i = o.Count - 1; i >= 0; i--)
            for (int j = 1; j <= i; j  )
            {
                IComparable o1 = o[j - 1];
                IComparable o2 = o[j];
                if (o1.CompareTo(o2) > 0)
                    o.Move(j - 1, j);
            }
    }
}

Usage::

someObservableCollection.BubbleSort();

CodePudding user response:

Im not sure if this UWP method of sorting is fully compatable with WinUI 3 as I haven't tried it. But the Contoso Orders Example https://github.com/microsoft/Windows-appsample-customers-orders-database has some sample code that changes the Datagrid when the Sorting Event is fired from the Datagrid. Refer to the DataGridHelper in the Views folder.

  • Related