I wanted to associate with ObservableCollection in XAML, and also apply grouping there. Basically, it worked well.
<UserControl.Resources> <CollectionViewSource x:Key="cvs" Source="{Binding Path=TestTemplates}"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="Title"/> </CollectionViewSource.SortDescriptions> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="TestCategory"/> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> </UserControl.Resources>
The data binding expression then became ItemsSource="{Binding Source={StaticResource ResourceKey=cvs}}" instead of ItemsSource="{Binding Path=TestTemplates}" .
At first, everything seemed cool until I wanted to update the user interface from the view model. The problem is that CollectionViewSource.GetDefaultView(TestTemplates) returns a different view than the XAML where the grouping was applied. Thus, I could not make a choice or do anything useful with it.
I could fix this by again linking the list directly to the property of the view model and adjusting the grouping in the code. But I'm not so happy with this decision.
private void UserControlLoaded(object sender, RoutedEventArgs e) { IEnumerable source = TemplateList.ItemsSource; var cvs = (CollectionView)CollectionViewSource.GetDefaultView(source); if (cvs != null) { cvs.SortDescriptions.Add(new SortDescription("Title", ListSortDirection.Ascending)); cvs.GroupDescriptions.Add(new PropertyGroupDescription("TestCategory")); } }
I guess the reason for this is already pointed out by John Skeet here .
However, I expect that there should be a way to get the right idea. I am wrong?
c # wpf xaml code-behind collectionviewsource
primfaktor
source share