Thursday, February 13, 2014

Sorting Evolution (5) - Sorting a WPF ListView/GridView by clicking on the header - Reusability

Fifth Generation

To reduce and to reuse the code in code-behind of the View we can extract it. The extracted code is moved in an own class that can be reused every time we want to add sorting indicators to a GridViewColumnHeader of a ListView.

private ListSortDirection _sortDirection;
private GridViewColumnHeader _sortColumn;

public string SetAdorner(object columnHeader)
  GridViewColumnHeader column = columnHeader as GridViewColumnHeader;
  if (column == null)
    return null;

  // Remove arrow from previously sorted header
  if (_sortColumn != null)
    var adornerLayer = AdornerLayer.GetAdornerLayer(_sortColumn);
    try { adornerLayer.Remove((adornerLayer.GetAdorners(_sortColumn))[0]); }
    catch { }

  if (_sortColumn == column)
    // Toggle sorting direction
    _sortDirection = _sortDirection == ListSortDirection.Ascending ?
                                       ListSortDirection.Descending :
    _sortColumn = column;
    _sortDirection = ListSortDirection.Ascending;

  var sortingAdorner = new SortingAdorner(column, _sortDirection);
  string header = string.Empty;

  // if binding is used and property name doesn't match header content
  Binding b = _sortColumn.Column.DisplayMemberBinding as Binding;
  if (b != null)
    header = b.Path.Path;

  return header;

The new class can be initiated in the constructor of the View.

private Sorting _sorter;

public SortingView()
  DataContext = new SortingViewModel();
  _sorter = new Sorting();

private void FifthResultDataViewClick(object sender, RoutedEventArgs e)
  string header = _sorter.SetAdorner(e.OriginalSource);
  var viewModel = DataContext as SortingViewModel;

The method SetAdorner is called in the GridViewCoumnHeader.Click event. In this method the Adorner is set. The method returns the property name that is binded to the column that should be sorted. The name is passed to the ViewModel that is sorting the column.

The source code can be downloaded from

Further Posts

  1. Sorting a WPF ListView/GridView by clicking on the header
  2. Sort Direction Indicators 
  3. Sort in ViewModel 
  4. Sort Direction Indicators with Adorners
  5. Reusability
  6. More Reusability
  7. Attached Property
  8. Behaviors (Expression Blend)

No comments:

Post a Comment