Search code examples
wpfdatagridvirtualization

WPF Datagrid, is it possible to have a mixture of Groups and plain (non grouped) rows?


I am using WPF Datagrid and have a requirement to show 10,000 rows, hence need virtualization. From several articles on StackOverflow I see that virtualization + grouping is not possible with the WPF Datagrid. This is because the Expander template to render a group cannot be virtualized.

In our system we may have 10,000 rows but only ever 3 or 4 are in each group. Also, the vast majority of rows are not grouped - they have a null GroupId. In a prototype I am working on these render as a group expander with no header. What I'd ideally like is those to be not grouped, just rows, and the rest rendered inside an expander. Is this possible?

WPF Datagrid with Grouped and Ungrouped rows


Solution

  • try this...

    <GroupStyle.ContainerStyle>
        <Style TargetType="{x:Type GroupItem}">
            <Style.Resources>
                <ControlTemplate x:Key="MultiItemGroupTemplate"
                                 TargetType="{x:Type GroupItem}">
                    <Expander IsExpanded="False">
                        <Expander.Header>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Path=Name}" />
                            </StackPanel>
                        </Expander.Header>
                        <ItemsPresenter />
                    </Expander>
                </ControlTemplate>
                <ControlTemplate x:Key="SingleItemGroupTemplate"
                                 TargetType="{x:Type GroupItem}">
                       <ItemsPresenter />
                </ControlTemplate>
            </Style.Resources>                                
            <Style.Triggers>
                <DataTrigger Binding="{Binding ItemCount}" Value="1">
                    <Setter Property="Template"
                            Value="{StaticResource SingleItemGroupTemplate}">
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
            <Setter Property="Template"
                    Value="{StaticResource MultiItemGroupTemplate}"/>
        </Style>
    </GroupStyle.ContainerStyle>
    

    Note: Please note that this will change for DataGrid... DataGrid's ItemPresenter is actually DataGridRowsPresenter