How to customize Group Header in DataGrid Grouping?
I have a DataGrid that looks something like this.
I have grouped data by Gen开发者_JAVA百科der. My GroupItem style is
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander x:Name="exp" IsExpanded="True"
Background="White"
Foreground="Black">
<Expander.Header>
<TextBlock Text="{Binding Name}"/>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I want my Group Header 'Male' and 'Female' to look like 'Gender : Male' and 'Gender : Female' instead of simple plain 'Male' and 'Female'. How can I modify my GroupItem style to achieve this so that every time I group my data in datagrid the group header can appear like GroupHeaderTitle : GroupHeaderValue? or Do I need to change anything other than GroupItem style to achieve this?
You can add a property GroupTitle
which represents the desired group title at your view model if you are using MVVM or to your Window code-behind otherwise, then add another TextBlock at the Expander.Header
which is bound to the GroupTitle
property, see the following code snippet:
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander x:Name="exp" IsExpanded="True"
Background="White" Foreground="Black">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=DataContext.GroupTitle}"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
When you add the grouping just supply a converter:
// Get the default view
ICollectionView view = CollectionViewSource.GetDefaultView(...);
// Do the grouping
view.GroupDescriptions.Clear();
view.GroupDescriptions.Add(new PropertyGroupDescription("Gender", new GenderConverter()));
// The converter
public class GenderConverter : IValueConverter
{
public object Convert(object value,
Type targetType, object parameter, CultureInfo culture)
{
return string.Format("Gender: {0}", value);
}
public object ConvertBack(object value,
Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
精彩评论