Home > Software engineering >  Display group header in DataGrid similar to regular row
Display group header in DataGrid similar to regular row

Time:04-29

There is such a task: to show the client records in a tabular form. These records can be grouped by one field. You need to display the group in such a way that the title and data of individual records are aligned in a regular table (example in the picture). The data is calculated in the view models, the task is to display it. There was an idea to do the following - to display the group header using the grid, with the description of the columns, the same as in the datagrid. And at first glance it turned out great - the data in the group header was aligned with the datagrid header. But when expanding the group (implemented by changing the visibility of the ItemsPresenter in the template for GroupStyle.ContainerStyle), it turned out that the row data within the group was aligned with an offset relative to the corresponding group header data. And when changing the width of the datagrid, this discrepancy is even more visible. While the idea is to dig towards its implementation of DataGridRowsPresenter with overriding the MeasureOverride and ArrangeOverride methods. But maybe someone knows an easier way. Example

CodePudding user response:

Found an easy way to get the desired result.

  1. Remove the header element from the Template description in GroupStyle.ContainerStyle. The template will only have a StackPanel with an ItemsPresenter inside.
  2. Add a fake entry to the ItemsSource that will act as a group header.
  3. Sort the ItemsSource so that the line with the "group header" is at the top.
  4. Use a StyleSelector which will apply the group header style to our fake group header row and the normal style to the rest of the rows. Here you can also make a binding for Visibility for ordinary rows and implement the group folding behavior through the bound property.
  5. Use DataTemplateSelector and DataGridTemplateColumn if the cells in this column are different for header and normal row. If you need to pass something to the ViewModel through the binding, then we use the RelativeSource and bind to the DataGridRow.
  • Related