Search code examples
wpfsortingdatatemplateitemscontrolcollectionviewsource

sorting a bound ItemsControl in a DataTemplate (XAML only)


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>

Solution

  • 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>