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...

10 comments:

  1. 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)

    ReplyDelete
  2. thanks! works perfectly!!!

    ReplyDelete
  3. Can't you achieve the same thing with:

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

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

    ReplyDelete
  5. 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.

    ReplyDelete
  6. Thanks. This did just what I was looking for!

    ReplyDelete
  7. If you use an ALT+key combo in the header to switch focus to the GroupBox, replace TextBox element with Label and change Text property to Content property.

    ReplyDelete