Thursday, December 4, 2008

Changing the text style of a WPF GroupBox header

I wanted to change the style of the header of a WPF GroupBox today and had to do a little digging to figure out how to do it.

The GroupBox header is not limited to just text - it can be any control. Because of this, no header text styling options are available directly as properties of the GroupBox control. Instead, you need to modify the DataTemplate of the GroupBox header.

Here is a style that will make the GroupBox header text black and bold:

<Style x:Key="MyGroupBoxStyle" TargetType="{x:Type GroupBox}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding}" Foreground="Black" FontWeight="Bold"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>


Note that this method is a bit of a hack, in that it assumes that your header is text. If it isn't, though, you've added your own custom controls to the header and you don't have a styling problem in the first place...

9 comments:

Brad said...

Kind of a hack I guess but if you were to Bind some other object to the Header property that wasn't text the Binding would silently fail (actually it would probably do a ToString on the Object and show Namespace.TypeName)

Gaurav Malik said...

nice code

brenda said...

thanks! works perfectly!!!

Benjamin said...

Can't you achieve the same thing with:

<GroupBox ... >
<GroupBox.Header>
<TextBlock Text="{Binding}" Foreground="Black" FontWeight="Bold"/>
</GroupBox.Header>
...
</GroupBox>

Mike said...

Sure, but the point here was to do it in a Style.

atoutsweb said...

Exactly what I was looking for.

Anonymous said...

This is Great, Thanks.

I was looking for something like this to style the groupbox globally.

How would you style the textblock to wrap the text? I added TextWrapping property but the text does not wrap.

Mel said...

Thanks. This did just what I was looking for!

Anonymous said...

thanks

Post a Comment