WPF: How to bind a CollectionViewSource within a DataTemplate

If you want to define a CollectionViewSource within a DataTemplate, you cannot set it directly in the DataTemplate itself, but rather in one of its child elements.

The reason for this is that the DataTemplate itself doesn’t become part of the visual tree and has no DataContext.

You have to define the resource in the scope of one of its elements, for example:

<DataTemplate x:Key="PeopleTemplate">
    <StackPanel>
        <StackPanel.Resources>
            <!-- Source -->
            <CollectionViewSource x:Key="PeopleViewSource" Source="{Binding People}">
                <CollectionViewSource.SortDescriptions>
                    <scm:SortDescription PropertyName="Name" Direction="Ascending" />
                </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>
        </StackPanel.Resources>
        <!-- Control -->
        <ListView ItemsSource="{Binding Source={StaticResource PeopleViewSource}}" />
    </StackPanel>
</DataTemplate>
Nuno Freitas
Posted by Nuno Freitas on April 16, 2014

Related articles