Is there a XAML only way to automatically sort the bound items (list of ViewModel object) ItemsControl based on one of the properties of the items. The ItemsControl is part of a DataTemplate. I thought CollectionViewSource would do the trick, but how do I bind the CollectionViewSource to the ItemsControl. The follwoing code dispays nothing:
<--xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"-->
<DataTemplate DataType="{x:Type vm:Company}">
<DataTemplate.Resources>
<CollectionViewSource x:Key="viewSource" Source="{Binding Employees}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="ID" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</DataTemplate.Resources>
<Viewbox>
<ItemsControl ItemsSource="{Binding Source={StaticResource viewSource}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Viewbox>
</DataTemplate>
Try moving the CollectionViewSource
resource to the scope of the Viewbox
rather than directly the DataTemplate
:
<DataTemplate DataType="{x:Type vm:Company}">
<Viewbox>
<Viewbox.Resources>
<CollectionViewSource x:Key="viewSource" Source="{Binding Employees}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="ID" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Viewbox.Resources>
<ItemsControl ItemsSource="{Binding Source={StaticResource viewSource}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Viewbox>
</DataTemplate>
I didn't use a DataTemplate or ViewBox to do this. You can choose the sort order by specifying an ItemsControl.Resource....
<ItemsControl xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
x:Name="MyItemsControl" Loaded="MyItemsControl_Loaded">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl>
<ItemsControl.Resources>
<CollectionViewSource x:Key="Orders" Source="{Binding Orders}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="OrderID" Direction="Ascending"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</ItemsControl.Resources>
<ItemsControl.ItemsSource>
<Binding Source="{StaticResource Orders}"/>
</ItemsControl.ItemsSource>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding OrderID}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With