1

在 WPF 中,我可以分组,但默认是升序分组。我需要能够控制组的排序(升序或降序)。例如:

第 1 组

  • 项目 1.1
  • 项目 1.2
  • 项目 1.3

第 2 组

  • 第 2.1 项
  • 第 2.2 项

并且还可以切换到:

第 2 组

  • 第 2.1 项
  • 第 2.2 项

第 1 组

  • 项目 1.1
  • 项目 1.2
  • 项目 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);
    }
    
4

1 回答 1

2

你有正确的想法。根据您分组的相同属性,将 SortDescription 添加到 ICollectionView。如果要更改排序方向,则必须清除现有方向并为相反方向添加新方向。一旦您发现它被创建,您就无法更改它。

于 2009-08-04T16:55:14.167 回答