Hi, I've got a grid where one of my columns shows an alphanumeric id and I want to sort the numbers correctly so I've implemented manual sorting. The bound data comes from a DataTable so I don't have a viewmodel for the rows. My sorting code, which I've hooked up to the Sorting-event, looks something like this:
private
void
OnGridViewSorting(
object
sender, GridViewSortingEventArgs e)
{
if
(e.Column.IsCustomSortingEnabled)
{
var dataView = (DataView)e.DataControl.ItemsSource;
if
(e.NewSortingState == SortingState.None)
{
// TODO: We should maybe reset sorting, not just return here.
return
;
}
if
(dataView.Table.Rows.Count > 0)
{
e.Cancel =
true
;
DataTable dtNew;
if
(e.OldSortingState == SortingState.None)
{
e.NewSortingState = SortingState.Ascending;
dtNew = dataView.Table.AsEnumerable().OrderBy(x => (
string
)x[e.Column.Name], GenericStringLogicalComparer.Default).CopyToDataTable();
}
else
{
e.NewSortingState = SortingState.Descending;
dtNew = dataView.Table.AsEnumerable().OrderByDescending(x => (
string
)x[e.Column.Name], GenericStringLogicalComparer.Default).CopyToDataTable();
}
var existingDataView = (DataView)
this
.ItemsSource;
for
(
int
n = 0; n < existingDataView.Table.Rows.Count; ++n)
{
// Just copy the item array instead of rebuilding table
existingDataView.Table.Rows[n].ItemArray = dtNew.Rows[n].ItemArray;
}
existingDataView.Table.AcceptChanges();
}
}
}
But I have two issues:
- When sorting on several columns I want to manage the sorting indices showing in the column headers, but I don't know how. It seems like they correspond to what's in the SortDescriptors collection. But I can't really edit the descriptors without adding some other sorting, can I? Is there some way to manually update the indices? Or set the SortDescriptors without really add another sort.
- We can store the state of grids to user-defined views, and do this by using the PersistenceManager to get xml describing the state of the grid. But since the sorting is defined by the SortDescriptors collection our manually sorting is not exported to xml.
I guess that both problems is about how I should edit the SortDescriptors when using the Sorting event.