How to: Sort and Group Data Using a View in XAML


This example shows how to create a view of a data collection in Extensible Application Markup Language (XAML). Views allow for the functionalities of grouping, sorting, filtering, and the notion of a current item.

In the following example, the static resource named places is defined as a collection of Place objects, in which each Place object is consisted of a city name and the state. The prefix src is mapped to the namespace where the data source Places is defined. The prefix scm maps to "clr-namespace:System.ComponentModel;assembly=WindowsBase" and dat maps to "clr-namespace:System.Windows.Data;assembly=PresentationFramework".

The following example creates a view of the data collection that is sorted by the city name and grouped by the state.


    <src:Places x:Key="places"/>

    <CollectionViewSource Source="{StaticResource places}" x:Key="cvs">
        <scm:SortDescription PropertyName="CityName"/>
        <dat:PropertyGroupDescription PropertyName="State"/>

The view can then be a binding source, as in the following example:

    <ListBox ItemsSource="{Binding Source={StaticResource cvs}}"
             DisplayMemberPath="CityName" Name="lb">
        <x:Static Member="GroupStyle.Default"/>

For bindings to XML data defined in an XmlDataProvider resource, precede the XML name with an @ symbol.

        <XmlDataProvider x:Key="myTasks" XPath="Tasks/Task">
                <Tasks xmlns="">
                    <Task Name="Groceries" Priority="2" Type="Home">

        <CollectionViewSource x:Key="mySortedTasks"
                              Source="{StaticResource myTasks}">
                <scm:SortDescription PropertyName="@Priority" />
                <dat:PropertyGroupDescription PropertyName="@Priority" />

Get the Default View of a Data Collection
Data Binding Overview
How-to Topics