views:

156

answers:

1

In WPF, I can group, but the default is group with ascending. One of my need to to be able to control the sorting of the group (Ascending or descending). For example:

group 1

  • item 1.1
  • item 1.2
  • item 1.3

group 2

  • item 2.1
  • item 2.2

and also be able to switch to:

group 2

  • item 2.1
  • item 2.2

group 1

  • item 1.1
  • item 1.2
  • item 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);
    
    }
+1  A: 

You had the right idea. Add a SortDescription to the ICollectionView based on the same property you are grouping on. If you want to change sort directions, you have to clear the existing one and add a new for the opposite direction. You can't change it once its created as you discovered.

Bryce Kahle