Search code examples
c#wpftask-parallel-librarytaskcollectionviewsource

CollectionViewSource.SortDescriptions not work when binding items are created using Parallel


I'm using VS2013, .net4.5, WPF desktop application.

Xaml:

    <CollectionViewSource x:Key="cvs" Source="{Binding ObsPasses, Mode=OneWay}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="StartDate"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>

cs:

            this.ObsPasses = new ObservableCollection<PassViewModel>(
            Passes.AsParallel().Select(x => new PassViewModel(x)));

If I remove .AsParallel(), then the items are sorted, if added, the items are in disorder. But I feel a little strange. Doesn't SortDescription guarantee the UI items to be sorted no matter in which order the items were added in background?


Solution

  • In your code Demo you didn't bind to CollectionViewSource, but to the collection itself. Try replacing

    <ItemsControl ItemsSource="{Binding ObsFoos, Mode=OneWay}" >
    

    with

    <ItemsControl ItemsSource="{Binding Source={StaticResource cvs}}" >