Wednesday, March 12, 2014

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

Sixth Generation

Now we want to extract the sorting method to an own class. So it can also reused every time we need sorting.

private ListSortDirection _sortDirection;
private string _sortColumnName;
private CollectionViewSource _dataView;

public void SetData<T>(IEnumerable<T> data)
{
  _dataView = new CollectionViewSource();
  _dataView.Source = data;
}

public ListCollectionView GetView()
{
  return (ListCollectionView)_dataView.View;
}

public void Sort(string column)
{
  if (_sortColumnName == column)
  {
    // Toggle sorting direction
    _sortDirection = _sortDirection == ListSortDirection.Ascending ?
                                       ListSortDirection.Descending :
                                       ListSortDirection.Ascending;
  }
  else
  {
    _sortColumnName = column;
    _sortDirection = ListSortDirection.Ascending;
  }

  _dataView.SortDescriptions.Clear();
  _dataView.SortDescriptions.Add(
                new SortDescription(_sortColumnName, _sortDirection));
}

The method SetData<T> expects an IEnumerable<T> that is used as source for a new created CollectionViewSource. The method GetView returns a ListCollectionView, the View of the CollectionViewSource. This can be used for binding in XAML. The method Sort takes a string as parameter that is the name of the property to be used for sorting. If this method is called, the CollectionViewSource will be sorted.

The code of the ViewModel can be reduced by using the new Sorting object.

private Sorting _sorter;
 
public SortingViewModel()
{
  _sorter = new Sorting();
}

private ObservableCollection<ResultData> _sixthResultData;

public ObservableCollection<ResultData> SixthResultData
{
  get
  {
    return _sixthResultData;
  }
  set
  {
    _sixthResultData = value;
    _sorter.SetData(_sixthResultData);
  }
}

public ListCollectionView SixthResultDataView
{
  get
  {
    return _sorter.GetView();
  }
}

public void Sort(string column)
{
  _sorter.Sort(column);
}

The Sorting object is instantiated in the constructor. Setting the data of the ViewModel also set the data of the Sorting object by calling SetData. An own property is used for binding the ListCollectionView retrieved by GetView. The Sort method calls the Sort method of the Sorting object.

The source code can be downloaded from http://code.msdn.microsoft.com/Sorting-a-WPF-ListView-by-a009edcb

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