ColumnHeader sorting with a CollectionViewSource

1.5k views Asked by At

I have a DataGrid that is data bound to a collection view source. If I bind the DataGrid to a List<T> I can automatically sort throught the columns of my DataGrid by clicking on the Column Header.

If bound to a CollectionViewSource the column headers still show up the indicates as the DataGrid would Sort, but it does not sort. How can I achieve the same functionality?

This is my DataGrid:

    <DataGrid Grid.Row="1" SelectedItem="{Binding SelectedItem}"
                  SelectionMode="Single" SelectionUnit="FullRow" AutoGenerateColumns="False" ItemsSource="{Binding CurrentErrorsViewSource.View}"
                  CanUserSortColumns="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False" IsReadOnly="True">
            <DataGrid.Columns>
                <DataGridTemplateColumn CanUserResize="False">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ContentControl Template="{StaticResource ErrorRemoteControl}" Foreground="{StaticResource GlyphBrush}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="{userInterface:Translation Description}" Binding="{Binding Path=(viewModels:ErrorItemViewModel.ErrorInformation).Description}" Width="Auto" />
                <DataGridTextColumn Header="{userInterface:Translation Code}" Binding="{Binding Path=(viewModels:ErrorItemViewModel.ErrorCode)}" Width="Auto" />
            </DataGrid.Columns>
      </DataGrid>
1

There are 1 answers

0
almulo On

You could handle the Sorting event of the DataGrid, and in code-behind create the appropiate SortDescription object and add them to your CollectionViewSource's SortDescriptions collection.

void SortHandler(object sender, DataGridSortingEventArgs e)
{
    var collectionViewSource = (sender as DataGrid).ItemsSource as CollectionViewSource;

    var propertyName = e.Column.SortMemberPath;
    var sortDirection = ListSortDirection.Ascending;

    foreach (var sortDescription in collectionViewSource.SortDescriptions)
        if (sortDescription.PropertyName == propertyName &&
            sortDescription.Direction == ListSortDirection.Ascending)
        {
            sortDirection = ListSortDirection.Descending;
            break;
        }

    var sortDescription = new SortDescription()
    {
        PropertyName = propertyName,
        Direction = sortDirection
    };

    collectionViewSource.SortDescriptions.Clear();
    collectionViewSource.SortDescriptions.Add(sortDescription);
}