Partager via


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.

Example

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 and dat are mapped to the System.ComponentModel and System.Windows.Data namespaces respectively.

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

<Window.Resources>

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

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

</Window.Resources>

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

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

To see the entire example, please see Collection View Source Sample.

See Also

Tasks

How to: Get the Default View of a Data Collection

Reference

CollectionViewSource

Concepts

Data Binding Overview

Other Resources

Data Binding Samples
Data Binding How-to Topics