Thursday, April 8, 2010

Preserve the previous sort order for WPF Datagrid

When you reload the WPF Datagrid's ItemsSource, the previous SortOrder is not retained. Here is a simple way you can preserve the sort order.

1. Before you reload the ItemsSource, save the sort column, sort direction as follows:

string dgSortDescription = null;
ListSortDirection? dgSortDirection = null;
int columnIndex = 0;
System.Collections.ObjectModel.ObservableCollection itemsColl= null;

foreach (DataGridColumn column in myDatagrid.Columns)
{

columnIndex++;

if (column.SortDirection != null)
{

dgSortDirection = column.SortDirection;

dgSortDescription = column.SortMemberPath;

break;
}

}



2. Now reload your collection with new data


itemsColl = new myNewcollection();

this.myDatagrid.ItemsSource = itemsColl;



3. Attach the saved sort description back as follows:



if(!string.IsNullOrEmpty(dgSortDescription) && dgSortDirection != null)

{

SortDescription s = new SortDescription(dgSortDescription, dgSortDirection.Value);

CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(myDatagrid.ItemsSource);
view.SortDescriptions.Add(s);

myDatagrid.Columns[columnIndex - 1].SortDirection = dgSortDirection;

}

No comments:

Post a Comment

Combinable Enumerations         [Flags]         public enum SomeFlags         {             NoColor = 0,             Red = 1,        ...