Search code examples
wpfxamlwpfdatagridgroupingexpander

How to Group a Datagrid without an Expander


I am working with the Datagrid grouping example here at MSDN. The code in the example uses an Expander to display child rows of a group. I don't want to use an Expander in my code. I want to always display every row. How can I display the child rows in a grouped datagrid without using an Expander control?


Solution

  • Instead of using Expander you can use Border.

     <DataGrid.GroupStyle>
                    <!-- Style for groups at top level. -->
                    <GroupStyle>
                        <GroupStyle.ContainerStyle>
                            <Style TargetType="{x:Type GroupItem}">
                                <Setter Property="Margin" Value="0,0,0,0"/>                            
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate TargetType="{x:Type GroupItem}">   
                                            <Border BorderThickness="1" BorderBrush="Black" CornerRadius="5,5,5,5" Margin="0,0,0,5">
                                                <StackPanel>
                                                    <StackPanel Height="30" Orientation="Horizontal">
                                                        <TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100" VerticalAlignment="Center"/>
                                                        <TextBlock FontWeight="Bold" Text="{Binding Path=ItemCount}" VerticalAlignment="Center" />
                                                    </StackPanel>
    
                                                    <ItemsPresenter />
                                                </StackPanel>
                                            </Border>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </GroupStyle.ContainerStyle>
                    </GroupStyle>
                    <!-- Style for groups under the top level. -->
                    <GroupStyle>
                        <GroupStyle.HeaderTemplate>
                            <DataTemplate>
                                <DockPanel Background="LightBlue">
                                    <TextBlock Text="{Binding Path=Name, Converter={StaticResource completeConverter}}" Foreground="Blue" Margin="30,0,0,0" Width="100"/>
                                    <TextBlock Text="{Binding Path=ItemCount}" Foreground="Blue"/>
                                </DockPanel>
                            </DataTemplate>
                        </GroupStyle.HeaderTemplate>
                    </GroupStyle>
     </DataGrid.GroupStyle>