SortDescriptions in Silverlight Datagrid

In Silverlight 3, we can specify add sortdescriptions indatagrid so that these columns are sorted initially when the datagrid loads. This can done in XAML as well as in code. The following code snippets demonstrate this behavior.

Specifying SortDescriptions in XAML

<UserControl x:Class="SortDescriptions3.MainPage"

   xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"

   xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"

   xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

   xmlns:scm="clr-namespace:System.ComponentModel;assembly=System.Windows"

   >

    <Grid x:Name="LayoutRoot" Background="White">

        <data:DataGrid x:Name="dg">

            <data:DataGrid.SortDescriptions>               

                <scm:SortDescription PropertyName="City" Direction="Descending" />

                <scm:SortDescription PropertyName="Department" Direction="Ascending" />

            </data:DataGrid.SortDescriptions>

        </data:DataGrid>

    </Grid>

</UserControl>

In the above code, we specified the column “City” to be sorted in Descending order, and the column “Department” to be sorted in Ascending order.

Specifying SortDescriptions through code

Defining SortDescriptions on PagedCollectionView

            List<Employee> list = PopulateData(100);

            PagedCollectionView cv = new PagedCollectionView(list);

            cv.GroupDescriptions.Add(new PropertyGroupDescription("City"));

            dg.ItemsSource = cv;

            cv.SortDescriptions.Add(new SortDescription("FirstName", ListSortDirection.Ascending));

            cv.SortDescriptions.Add(new SortDescription("Department", ListSortDirection.Descending));

 

We can combine sort Descriptions as well as GroupDescriptions (to specify column grouping) as indicated in the above code.

Defining SortDescriptions on datagrid

            List<Employee> list = PopulateData(100);

            dg.ItemsSource = list;

            dg.SortDescriptions.Add(new SortDescription("City", ListSortDirection.Descending));

            dg.SortDescriptions.Add(new SortDescription("Department", ListSortDirection.Ascending));

 

DataGridSortDescriptions 

Hooking up the code pieces together and building the application and running it will show us sorting in datagrid.