26

I have a DataGrid in WPF app with several columns, including a Name column. If the users switches to a particular view, I want the data to be pre-sorted by Name (and I'd like a sort arrow to appear in the Name header just as if the user had clicked that header). However, I can't find the expected properties to make this happen. I was looking for something like SortColumn, SortColumnIndex, SortDirection, etc.

Is it possible to specify the default sort column and direction in markup (XAML) or is that not supported by the WPF Toolkit DataGrid?

devuxer
  • 41,681
  • 47
  • 180
  • 292
  • Since WPF doesn't come with a DataGrid built in, can we assume you're referring to the DataGrid that comes with WPF Toolkit (http://www.codeplex.com/wpf)??? – Drew Marsh Oct 26 '09 at 20:30
  • Yes, I put the wpftoolkit tag, but I guess I didn't mention it in my question. I'll add that. – devuxer Oct 26 '09 at 20:45

5 Answers5

48

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}}">
DLeh
  • 23,806
  • 16
  • 84
  • 128
Drew Marsh
  • 33,111
  • 3
  • 82
  • 100
  • @Drew, thanks but the `SortMemberPath` just specifies which field in the data source goes with which column in the DataGrid. I need to set the *current* sort column (and direction). E.g., this DataGrid is currently sorted ascending by Name. – devuxer Oct 26 '09 at 20:43
  • 1
    Well that how you solve your "clicking the header column and sorting problem". I accidentally left out how to initially sort the grid, I will add to my answer now. – Drew Marsh Oct 26 '09 at 20:52
  • 5
    Yes :) That's much closer to what I was looking for, thanks. The only problem is that the sort arrow doesn't appear in the header of the column the table is sorted by. I can live with that, but an arrow would make it a little clearer to the user what the sort column is. Just a note for anyone trying to do this, you need a reference to `WindowsBase` to use `System.ComponentModel`. Once you've added the reference, you need this: `xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"`. – devuxer Oct 26 '09 at 21:58
  • 12
    I had to use to get this to work. – Samuel Jack May 12 '10 at 15:49
18

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

Community
  • 1
  • 1
Matt
  • 261
  • 3
  • 5
  • 1
    This does mean that the `SortDirection` property must manually match the columns in the `SortDescription` - is there any way for the DataGrid to detect the CollectionViewSource's sorting and display the indicators automatically? – Dai Nov 02 '17 at 03:22
5

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>
LPL
  • 16,827
  • 6
  • 51
  • 95
Sukhjeet
  • 51
  • 1
  • 2
    I keep coming back to this post (3rd time this year) because I forget to do this very important part/piece of the puzzle! Thank you for posting it. – denis morozov Jul 10 '12 at 16:25
3

When you see ItemsSource doesn't support CollectionViewSource exception, you can sort collection by Linq before you refer it to a DataGrid:

ObservableCollection<MyDataClass> myCollection = new ObservableCollection<MyDataClass>();
dataGrid.ItemsSource = from item in myCollection orderby item select item;

You have to implement IComparable interface to MyDataClass:

public class MyDataClass : IComparable<MyDataClass> {
    public int CompareTo(Classified other) {
        return other.Value.CompareTo(this.Value); // DESC
        return this.Value.CompareTo(other.Value); // ASC
    }
}
Václav Dajbych
  • 2,584
  • 2
  • 30
  • 45
  • This actually worked for me as I was trying to order a BindlingList using Lambda. This worked, Lambda didn't! – DerpyNerd Feb 12 '15 at 22:00
0

This works for me.

ListSortDirection sortDirection;
int selectedColumnIndex;
private void customerDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
    selectedColumnIndex = e.Column.DisplayIndex;
    sortDirection = (e.Column.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending: ListSortDirection.Ascending);
}

private void applySortDescriptions(ListSortDirection listSortDirection)
{
    //Clear current sort descriptions 
    customerDataGrid.Items.SortDescriptions.Clear();

    //Get property name to apply sort based on desired column 
    string propertyName = customerDataGrid.Columns[selectedColumnIndex].SortMemberPath;

    //Add the new sort description 
    customerDataGrid.Items.SortDescriptions.Add(new SortDescription(propertyName, listSortDirection));

    //apply sort 
    applySortDirection(listSortDirection);

    //refresh items to display sort 
    customerDataGrid.Items.Refresh();
}

private void applySortDirection(ListSortDirection listSortDirection)
{
    customerDataGrid.Columns[selectedColumnIndex].SortDirection = listSortDirection;
}