Alexey Titov
Alexey Titov

Reputation: 353

DataGrid append another column sort

I have a WPF project - a datagrid with four columns: ColumnOne, ColumnTwo, columnThree, ColumnFour. Is it possible that when user sorts by ColumnOne or ColumnTwo - then code behind adds sorting by ColumnThree as well, so it gets sorted like SortBy("ColumnOne").ThenBy("ColumnThree"). If that matters, ItemsSource for my DataGrid is PagedCollectionView, which supports SortDescriptors.

Upvotes: 0

Views: 61

Answers (1)

user6996876
user6996876

Reputation:

You have to override DataGrid.OnSorting like in this simple example (but please extend it to your full requirements) and use the custom control instead of the standard DataGrid in your XAML.

public class MyDataGrid : DataGrid
    {
        protected override void OnSorting(DataGridSortingEventArgs eventArgs)
        {
            base.OnSorting(eventArgs);
            var test = eventArgs.Column;
            if (test.Header.ToString() == "ColumnOne" && test.SortDirection.HasValue
                && test.SortDirection.Value.Equals(ListSortDirection.Ascending)
                )
            {
                ICollectionView view = CollectionViewSource.GetDefaultView(this.ItemsSource);
                view.SortDescriptions.Add(new SortDescription("ColumnThree", ListSortDirection.Ascending));
                view.Refresh();

                this.Columns[2].SortDirection = ListSortDirection.Ascending;
            }
        }
    }

The above code handles both the colletion sorting and the SortDirection property setting for ColumnThree in just one case: when the user orders by ColumnOne ascending.

Upvotes: 1

Related Questions