Reputation: 935
There's a lot of discussion about Filtering, Grouping and Sorting on CollectionViewSource in WPF, and what is an isn't "MVVM"-practical (especially when adding Filters in code-behind).
I want to have ViewModel control over these properties (like adding sort and filter descriptors), but in order to use SynchronizationContext
with an Asynchronous ObservableCollection, I need the CollectionViewSource instantiated in the View (on the dispatcher thread), NOT instantiated in the model - but the model needs access to the CollectionViewSource in order to add filter, group and sort descriptors from code, rather than defining them in XAML.
For this purpose, I'd like to find a way to Bind the XAML-declared CollectionViewSource object BACK to the ViewModel. Something like this:
<UserControl.Resources>
<CollectionViewSource
IsLiveFilteringRequested="True"
x:Name="collectionViewSource"
x:Key="collectionViewSource"
Source="{Binding DataContext.myCollection, IsAsync=True}"
Binding="{Binding DataContext.myCollectionViewSourceProperty, Mode=OneTime}" />
</UserControl.Resources>
Of course, the CollectionViewSource doesn't have a "Binding" property, and the source must point to an ObservableCollection.
Is there a way to accomplish this?
Upvotes: 2
Views: 1122
Reputation: 2003
My initial thought was leave the CollectionViewSource
defined in - and instantiated by - XAML and then to use some form of attached property to bind the filters, groups and sorting properties to values on the view model. Sure enough this has already been done (and seems to work) as can be found here.
This should resolve your issue as the CollectionViewSource
will be instantiated on the Dispatcher thread but can be controlled from the view model (ensuring that bound property changes also occur on the dispatcher thread).
Upvotes: 1