Search code examples
wpfentity-frameworkdatagridgroupingexpander

Datagrid expander (from grouping) header


Following this tutorial I had an idea to put in the Expander Header more data. I have 2 tables (Document 1 - * Entry). I'm displaying the Entries grouped by Documents and I don't want some data to be repeated in the datagrid so I thought to place it in the expander header.

<DataGrid.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Path=Name}" />
                        </StackPanel>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
                <GroupStyle.ContainerStyle>
                    <Style TargetType="{x:Type GroupItem}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type GroupItem}">
                                    <Expander IsExpanded="True">
                                        <Expander.Header>
                                            <StackPanel Orientation="Horizontal">
                                                <TextBlock Text="{Binding Path=Name}" />
                                                <TextBlock Text=" - "/>
                                                **<TextBlock Text="{Binding Path=Document.Number or Name2}"/>**
                                            </StackPanel>
                                            ...

Solution

  • You can do this:

    <Expander.Header>
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GroupItem}}, Converter={StaticResource ResourceKey=groupToTitleConverter}}" />
    </StackPanel> </Expander.Header>
    

    Converter:

    public class GroupToTitleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            GroupItem groupItem = value as GroupItem;
            CollectionViewGroup collectionViewGroup = groupItem.Content as CollectionViewGroup;
            EntryViewModel entryViewModel = collectionViewGroup.Items[0] as EntryViewModel;
            string title = string.Format("{0} - {1} {2}", entryViewModel.Id, entryViewModel.Numar, entryViewModel.Obiect);
            return title;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Taking first item from collection in group to form header title might not be the most elegant solution but it will serve the purpose.

    Full code is available here: ExpanderHeadersInDataGridGroupStyle.zip