Search code examples
wpfsortingcollectionviewsource

I need CollectionViewSource Sorting/LiveSorting Clarification


I have been searching on this, but I can't find anything that actually clears it up for me.

What is the interaction between the SortDescription collection and the LiveSortingProperties?

Does LiveSorting rely on the existence of SortDescriptions to determine ASC/DESC order? Are the live sorting properties just a specification on which properties to watch for changes?

If I want to change the sort basis, do I clear the SortDescription collection and then add new ones and "Refresh" the view?

Do you need LiveSorting to handle additions/deletions to the underlying ObservableCollection or just in case certain properties of objects already in the collection change?


Solution

  • What is the interaction between the SortDescription collection and the LiveSortingProperties?

    The LiveSortingProperties come from the CollectionViewSource and listen on your items (which must implement INotifyPropertyChanged) for changes of the specific properties; if they are changed, the view is automatically updated. It is important that you also set IsLiveSortingRequested = true after adding the LiveSortingProperties so it will setup everything required (the listeners). The LiveSortingProperties are independent from the SortDescriptions, the SortDescriptions do the sorting and the LiveSortingProperties update the view on changes.

    Something nice to know: The sorting is done by the ICollectionView and the live updating is done by the ICollectionViewLiveShaping. The CollectionViewSource is just a proxy which calls the methods/changes properties of the interfaces. The ListCollectionView is the default implementation of the ICollectionView and ICollectionViewLiveShaping.

    Does LiveSorting rely on the existence of SortDescriptions to determine ASC/DESC order? Are the live sorting properties just a specification on which properties to watch for changes?

    As you said, the LiveSortingProperites are just watchers: you can add there properties you are not sorting and the view will update when these properties change.

    If I want to change the sort basis, do I clear the SortDescription collection and then add new ones and "Refresh" the view?

    The best would be something like that (Microsoft is doing the same):

        using (collectionViewSource.DeferRefresh())
        {
            collectionViewSource.SortDescriptions.Clear();
            collectionViewSource.SortDescriptions.Add(new SortDescription("Foo"));
        }
    

    Do you need LiveSorting to handle additions/deletions to the underlying ObservableCollection or just in case certain properties of objects already in the collection change?

    Deletions/Additions are handled automatically, if the live sorting on a property is enabled, it will be enabled on all items, including new items.