在WPF中,我可以分组,但默认为具有升序的组。我需要能够控制组的排序(升序或降序)。例如:
第1组
第2组
也可以切换到:
第2组
第1组
第1.3项
//Here is the function to setup a group for a particular column:
private void SetupGrouping(DataGrid parentGrid, DataGridColumn col)
{
if (parentGrid == null || col == null || string.IsNullOrEmpty(col.SortMemberPath))
return;
ICollectionView vw = GetDefaultView();
if (vw != null && vw.CanGroup)
{
if (vw.GroupDescriptions.Count != 0)
{
vw.GroupDescriptions.Clear();
}
PropertyGroupDescription gd = new PropertyGroupDescription(col.SortMemberPath);
// Check to see if the column is Priority, if it is
// then do the grouping with high priority (3) on top.
// The order should be High(3), Normal (2), Low(1)
DataGridColumn priCol = GetColumnByID(ColumnFlags.Priority);
if(col == priCol)
{
// Attempted to change the direction of the sort added by adding group.
// However, it has error complaining SortDescription is sealed
// and can't be changed.
//if (vw.SortDescriptions != null && vw.SortDescriptions.Count > 0)
//{
// SortDescription sd = vw.SortDescriptions[0];
// if (sd.PropertyName == col.SortMemberPath)
// {
// sd.Direction = ListSortDirection.Descending;
// }
//}
}
// Info: when we add a new GroupDescription to GroupDescriptions list,
// guest what? a new SortDescription is also added to the
// SortDescriptions list.
vw.GroupDescriptions.Add(gd);
}
// Save off the column for later use
GroupedColumn = col;
// Set the DataGrid's Tag so that the GroupSyle can get the column name
parentGrid.Tag = DispatchAttachedProperties.GetColumnHeader(col);
}
答案 0 :(得分:2)
你有正确的想法。根据您要分组的相同属性,将SortDescription添加到ICollectionView。如果要更改排序方向,则必须清除现有排序方向并为相反方向添加新方向。一旦发现,就无法更改它。