Pre-sorting a DataGrid in WPF Pre-sorting a DataGrid in WPF wpf wpf

Pre-sorting a DataGrid in WPF


Assuming you're talking about the WPF Toolkit DataGrid control, you need only set the CanUserSortColumns property to true and then set the SortMemberPath property of each DataGridColumn in the DataGrid.

As far as sorting the collection initially, you must use a CollectionViewSource and set the sort on that and then assign that as the ItemsSource of your DataGrid. If you're doing this in XAML then it would be as easy as:

<Window.Resources>    <CollectionViewSource x:Key="MyItemsViewSource" Source="{Binding MyItems}">        <CollectionViewSource.SortDescriptions>           <scm:SortDescription PropertyName="MyPropertyName"/>        </CollectionViewSource.SortDescriptions>    </CollectionViewSource></Window.Resources><DataGrid ItemsSource="{StaticResource MyItemsViewSource}"></DataGrid>

NOTE: the "scm" namespace prefix maps to System.ComponentModel where the SortDescription class lives.

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

EDIT: I think enough people got help from this post, that this upvoted comment should be included in this answer:

I had to use this to get it to work:

<DataGrid ItemsSource="{Binding Source={StaticResource MyItemsViewSource}}">


I know this is an old post but in addition to Drew Marsh's answer and in response to DanM's issue with the column header's arrows not appearing... You need to add the SortDirection property to the DataGridColumn:

<DataGridTextColumn Header="Name" Binding="{Binding Name}" SortDirection="Ascending" />

I posted a question about this and found the answer a few days later:

ColumnHeader arrows not reflected when sorting a DataGrid in XAML


When you see ItemsSource doesn't support CollectionViewSource exception then you can set the DataContext of DataGrid as 'MyItemsViewSource' and ItemsSource as {Binding} like this:

<DataGrid DataContext="{StaticResource MyItemsViewSource}" ItemsSource="{Binding}"></DataGrid>