2
votes

In my Silverlight application, I have a DataGrid that shows a list of projects. It is data-bound to a custom ObservableCollection which implements ICollectionView to provide SortDescription's.

When the user clicks on a header, the data is sorted by this column in ascending order. Most users expect alphabetical sort (ASC) for column "Name", but for "Creation Date" it makes more sense to show latest entries first (DESC).

Is it possible to override the default sorting order for some of the columns?

1
@icebat, the solution from there is not applicable: DataGrid for Silverlight does not have a Sorting event. - Impworks
Oh, you're right. My bad. - icebat

1 Answers

0
votes

You've got two options here, that I can see. You can extend ObservableCollection with custom sort functions for the grid in question. You can see how to do that here.

Your other option involves customizing the grid with hyperlink buttons in the header. You can then capture the click and sort the underlying collection any way you want.

UI CODE

<my:DataGrid.Columns>
    <my:DataGridTextColumn DisplayMemberBinding="{Binding Name}">
        <my:DataGridTextColumn.Header>
            <HyperlinkButton Content="Name" Tag="Name"
                Click="Sort_Click" TextDecorations="Underline"/>
        </my:DataGridTextColumn.Header>
    </my:DataGridTextColumn>
    <my:DataGridTextColumn DisplayMemberBinding="{Binding CreationDate}">
        <my:DataGridTextColumn.Header>
            <HyperlinkButton Content="CreationDate" Tag="CreationDate"
                Click="Sort_Click" TextDecorations="Underline"/>
        </my:DataGridTextColumn.Header>
    </my:DataGridTextColumn>
</my:DataGrid.Columns>

Click Handlder

private void Sort_Click(object sender, RoutedEventArgs e)
{
    HyperlinkButton button = sender as HyperlinkButton;
    //  Which property are we sorting?
    string sortProperty = button.Tag.ToString();
    //  sort direction (variable to keep track of which way were sorting last, add key checking an null checking)
    bool sortAsc = !this.columnSortState[sortProperty];
    IEnumerable<ITEMS> dataItems = dataGrid.ItemsSource as IEnumerable<ITEMS>;
    switch (sortProperty)
    {
        case "Name":
            dataItems = sortAsc
                ? dataItems.OrderBy(x => x.Name)
                : dataItems.OrderByDescending(x => x.Name);
            break;
        case "CreationDate":
            dataItems = sortAsc
                ? dataItems.OrderByDescending(x => x.CreationDate);
                : dataItems.OrderBy(x => x.CreationDate)
            break;
    }

    this.columnSortState[sortProperty] = isSortAsc;
}

I've taken out all the null checking and other stuff you should be doing in the Click Handler for brevity.