sorting a bound ItemsControl in a DataTemplate (XAML only)

bitbonk picture bitbonk · Aug 28, 2009 · Viewed 11k times · Source

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>

Answer

Kent Boogaart picture Kent Boogaart · Aug 29, 2009

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>