UWP ObservableCollection sorting and grouping : <p>In UWP apps, how can you group and sort an ObservableCollection and keep all the live notification goodness?  </p>

<p>In most simple UWP examples I've seen, there is generally a ViewModel that exposes an ObservableCollection which is then bound to a ListView in the View. 
When items are added or removed from the ObservableCollection, the ListView automatically reflects the changes by reacting to the INotifyCollectionChanged notifications. This all works fine in the case of an unsorted or ungrouped ObservableCollection, but if the collection needs to be sorted or grouped, there seems to be no readily apparent way to preserve the update notifications. What's more, changing the sort or group order on the fly seems to throw up significant implementation issues.</p>

<p>++  </p>

<p>Take a scenario where you have an existing datacache backend that exposes an ObservableCollection of very simple class Contact.</p>

<pre><code>public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string State { get; set; }
}
</code></pre>

<p>This ObservableCollection changes over time, and we want to present a realtime grouped and sorted list in the view that updates
in response to changes in the datacache. We also want to give the user the option to switch the grouping between LastName and State on the fly.</p>

<p>++</p>

<p>In a WPF world, this is relatively trivial. 
We can create a simple ViewModel referencing the datacache that presents the cache's Contacts collection as-is.</p>

<pre><code>public class WpfViewModel 
{
    public WpfViewModel()
    {
        _cache = GetCache();
    }

    Cache _cache;

    public ObservableCollection&lt;Contact&gt; Contacts
    {
        get { return _cache.Contacts; }
    }
}
</code></pre>

<p>Then we can bind this to a view where we implement a CollectionViewSource and Sort and Group definitions as XAML resources.</p>

<pre><code>&lt;Window .....
   xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"&gt;

   &lt;Window.DataContext&gt;
      &lt;local:WpfViewModel /&gt;
   &lt;/Window.DataContext&gt;

    &lt;Window.Resources&gt;
        &lt;CollectionViewSource x:Key="cvs" Source="{Binding Contacts}" /&gt;
        &lt;PropertyGroupDescription x:Key="stategroup" PropertyName="State" /&gt;
        &lt;PropertyGroupDescription x:Key="initialgroup" PropertyName="LastName[0]" /&gt;
        &lt;scm:SortDescription x:Key="statesort" PropertyName="State" Direction="Ascending" /&gt;
        &lt;scm:SortDescription x:Key="lastsort" PropertyName="LastName" Direction="Ascending" /&gt;
        &lt;scm:SortDescription x:Key="firstsort" PropertyName="FirstName" Direction="Ascending" /&gt;
    &lt;/Window.Resources&gt;

    &lt;Grid&gt;
        &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height="*" /&gt;
            &lt;RowDefinition Height="Auto" /&gt;
        &lt;/Grid.RowDefinitions&gt;

        &lt;ListView ItemsSource="{Binding Source={StaticResource cvs}}"&gt;
            &lt;ListView.ItemTemplate&gt;
                &lt;DataTemplate&gt;
                    &lt;Grid&gt;
                        &lt;Grid.ColumnDefinitions&gt;
                            &lt;ColumnDefinition Width="100" /&gt;
                            &lt;ColumnDefinition Width="100" /&gt;
                            &lt;ColumnDefinition Width="*" /&gt;
                        &lt;/Grid.ColumnDefinitions&gt;
                        &lt;TextBlock Text="{Binding LastName}" /&gt;
                        &lt;TextBlock Text="{Binding FirstName}" Grid.Column="1" /&gt;
                        &lt;TextBlock Text="{Binding State}" Grid.Column="2" /&gt;
                    &lt;/Grid&gt;
                &lt;/DataTemplate&gt;
            &lt;/ListView.ItemTemplate&gt;
            &lt;ListView.GroupStyle&gt;
                &lt;GroupStyle&gt;
                    &lt;GroupStyle.HeaderTemplate&gt;
                        &lt;DataTemplate&gt;
                            &lt;Grid Background="Gainsboro"&gt;
                                &lt;TextBlock FontWeight="Bold" 
                                           FontSize="14" 
                                           Margin="10,2"
                                           Text="{Binding Name}"/&gt;
                            &lt;/Grid&gt;
                        &lt;/DataTemplate&gt;
                    &lt;/GroupStyle.HeaderTemplate&gt;
                &lt;/GroupStyle&gt;
            &lt;/ListView.GroupStyle&gt;
        &lt;/ListView&gt;

        &lt;StackPanel Orientation="Horizontal" Grid.Row="1"&gt;
            &lt;Button Content="Group By Initial" Click="InitialGroupClick" /&gt;
            &lt;Button Content="Group By State" Click="StateGroupClick" /&gt;
        &lt;/StackPanel&gt;

    &lt;/Grid&gt;
&lt;/Window&gt;
</code></pre>

<p>Then when the user clicks on the GroupBy buttons at the bottom of the window we can we can group and sort on the fly in code-behind.</p>

<pre><code>private void InitialGroupClick(object sender, RoutedEventArgs e)
{
     var cvs = FindResource("cvs") as CollectionViewSource;
     var initialGroup = (PropertyGroupDescription)FindResource("initialgroup");
     var firstSort = (SortDescription)FindResource("firstsort");
     var lastSort = (SortDescription)FindResource("lastsort");

     using (cvs.DeferRefresh())
     {
         cvs.GroupDescriptions.Clear();
         cvs.SortDescriptions.Clear();
         cvs.GroupDescriptions.Add(initialGroup);
         cvs.SortDescriptions.Add(lastSort);
         cvs.SortDescriptions.Add(firstSort);
     }
}

private void StateGroupClick(object sender, RoutedEventArgs e)
{
     var cvs = FindResource("cvs") as CollectionViewSource;
     var stateGroup = (PropertyGroupDescription)FindResource("stategroup");
     var stateSort = (SortDescription)FindResource("statesort");
     var lastSort = (SortDescription)FindResource("lastsort");
     var firstSort = (SortDescription)FindResource("firstsort");

     using (cvs.DeferRefresh())
     {
         cvs.GroupDescriptions.Clear();
         cvs.SortDescriptions.Clear();
         cvs.GroupDescriptions.Add(stateGroup);
         cvs.SortDescriptions.Add(stateSort);
         cvs.SortDescriptions.Add(lastSort);
         cvs.SortDescriptions.Add(firstSort);
     }
}
</code></pre>

<p>This all works fine, and the items are updated automatically as the data cache collection changes. The Listview grouping and selection remains unaffected by collection changes, and the new contact items are correctly grouped.The grouping can be swapped between State and LastName initial by user at runtime.</p>

<p>++</p>

<p>In the UWP world, the CollectionViewSource no longer has the GroupDescriptions and SortDescriptions collections, and sorting/grouping need to be carried out at the ViewModel level. The closest approach to a workable solution I've found is along the lines of Microsoft's sample package at</p>

<p><a href="https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/XamlListView" rel="noreferrer">https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/XamlListView</a></p>

<p>and this article</p>

<p><a href="http://motzcod.es/post/94643411707/enhancing-xamarinforms-listview-with-grouping" rel="noreferrer">http://motzcod.es/post/94643411707/enhancing-xamarinforms-listview-with-grouping</a></p>

<p>where the ViewModel groups the ObservableCollection using Linq and presents it to the view as an ObservableCollection of grouped items</p>

<pre><code>public ObservableCollection&lt;GroupInfoList&gt; GroupedContacts
{
    ObservableCollection&lt;GroupInfoList&gt; groups = new ObservableCollection&lt;GroupInfoList&gt;();

    var query = from item in _cache.Contacts
                group item by item.LastName[0] into g
                orderby g.Key
                select new { GroupName = g.Key, Items = g };

    foreach (var g in query)
    {
         GroupInfoList info = new GroupInfoList();
         info.Key = g.GroupName;
         foreach (var item in g.Items)
         {
             info.Add(item);
         }
         groups.Add(info);
    }

    return groups;
}
</code></pre>

<p>where GroupInfoList is defined as </p>

<pre><code>public class GroupInfoList : List&lt;object&gt;
{
   public object Key { get; set; }
}
</code></pre>

<p>This does at least get us a grouped collection displayed in the View, but updates to the datacache collection are no longer reflected in real time. We could capture the datacache's CollectionChanged event and use it in the viewmodel to refresh the GroupedContacts collection, but this creates a new collection for every change in the datacache, causing the ListView to flicker and reset selection etc which is clearly suboptimal.</p>

<p>Also swapping the grouping on the fly would seem to require a completely seperate ObservableCollection of grouped items for each grouping scenario, and for the ListView's ItemSource binding to be swapped at runtime.</p>

<p>The rest of what I've seen of the UWP environment seems extremely useful, so I'm surprised to find something as vital as grouping and sorting lists throwing up obstacles...</p>

<p>Anyone know how to do this properly?</p>
