Telerik RADGrid and sorting
I'm using the RADGridView for WPF to display some data. It is pulled dynamically from DB so I don't know column names or the type of data contained in each cell. I want to let the user sort the data on each column when it double-clicks on a column header.
For some reason the grid doesn't sort. This is what I have so far.
private void SetEventHandlers()
{
if (_grid != null)
{
_grid.AddHandler(GridViewCellBase.CellDoubleClickEvent, new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick), true);
}
}
private void OnCellDoubleClick(object sender, RoutedEventArgs e)
{
GridViewCellBase cell = e.OriginalSource as GridViewCellBase;
if (cell != null && cell is GridViewHeaderCell)
{
SetSorting(cell);
}
}
private void SetSorting(GridViewCellBase cell)
{
GridViewColumn column = cell.Column;
开发者_JAVA技巧 SortingState nextState = GetNextSortingState(column.SortingState);
_grid.SortDescriptors.Clear();
if (nextState == SortingState.None)
{
column.SortingState = SortingState.None;
}
else
{
_grid.SortDescriptors.Add(CreateColumnDescriptor(column, nextState));
column.SortingState = nextState;
}
}
EDIT:
private ColumnSortDescriptor CreateColumnDescriptor(GridViewColumn column, SortingState sortingState)
{
ColumnSortDescriptor descriptor = new ColumnSortDescriptor();
descriptor.Column = column;
if (sortingState == SortingState.Ascending)
{
descriptor.SortDirection = ListSortDirection.Ascending;
}
else
{
descriptor.SortDirection = ListSortDirection.Descending;
}
return descriptor;
}
It turned out than my RadGrid data was binded to an ObservableCollection. Sorting functionality of the grid itself did not work. Sorting the ObservableCollection was the solution. I ended up sorting the ObservableCollection using linq.
精彩评论