Here is a short sample on how to create a tri-state sorting experience with the WPF DataGrid.  In the current design, when clicking on a column header it will toggle sorting of the column starting from ascending to descending.  Unfortunately you cannot get back to the original state without adding your own custom logic for it.  To get back to the original state you have to set the column.SortDirection back to null and clear out the SortDescriptions that were added when you click on the column header.  In this sample I decided to add one more toggle state so when you click on the column header a third time it goes back to the original state.  I’m adding this functionality to the DataGrid.Sorting event and stop the default sort if the toggle state is going back to the original state.  Here is the code:       

private void DataGrid_Standard_Sorting(object sender, DataGridSortingEventArgs e)

{

  DataGrid dataGrid = sender as DataGrid;

  string sortPropertyName = Helpers.GetSortMemberPath(e.Column);

  if (!string.IsNullOrEmpty(sortPropertyName))

  {

    // sorting is cleared when the previous state is Descending

    if (e.Column.SortDirection.HasValue && e.Column.SortDirection.Value == ListSortDirection.Descending)

    {
      int
index = Helpers.FindSortDescription(dataGrid.Items.SortDescriptions, sortPropertyName);

      if (index != -1)

      {
          e.Column.SortDirection = null;

 

          // remove the sort description

          dataGrid.Items.SortDescriptions.RemoveAt(index);

          dataGrid.Items.Refresh();

 

          if ((Keyboard.Modifiers & ModifierKeys.Shift) != ModifierKeys.Shift)

          {
             // clear any other sort descriptions for the multisorting case

             dataGrid.Items.SortDescriptions.Clear();

             dataGrid.Items.Refresh();
          }

 

          // stop the default sort

          e.Handled = true;

      }
    }
  }

}

 

I also decided to add some extra functionality for displaying the sort order of the column when doing multi-column sorting.  By default when you do multi-column sorting you really have no idea which column is sorted in which order as it only shows that direction triangle.  I just add text to the header but you can always get creative and add all that WPF eye candy.  Here is a screenshot:

sortingOrder

The full sample is here.

Other DataGrid Samples:

ScrollViewer with ToolTip

Custom sorting, column selection, single-click editing

Styling rows and columns based on header conditions

Clipboard Copy