How to use style for GroupBox header?

2020-06-08 05:40发布

问题:

I have lost of GroupBox in my form that their header text must be Bold. I know how to do it for a single GroupBox:

<GroupBox>
     <GroupBox.Header>
         <TextBlock Text="HEADER TEXT" FontWeight="Bold"/>
     </GroupBox.Header>
</GroupBox> 

But I'm interested to know how to do it with Styles. Here is what I have tried:

<Style TargetType="GroupBox">
    <Setter Property="BorderBrush" Value="{StaticResource lightBlueBrush}"/>
    <Setter Property="Margin" Value="25,1,5,5"/>
    //<Setter ??
</Style>

I have tried <Setter Property="HeaderTemplate" Value={StaticResource myTemp}> Which myTemp is a simple DataTemplate But VS suddenly closed! I'm not sure if I'm in the correct way of doing it, so anyone could help me?

EDIT: Please test your idea before posting it as an answer!

回答1:

Did you try the following?

<Style TargetType="GroupBox">
    <Setter Property="BorderBrush" Value="{StaticResource lightBlueBrush}"/>
    <Setter Property="Margin" Value="25,1,5,5"/>
    <Setter Property="HeaderTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock Text="{Binding}" FontWeight="Bold"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

Usage:

<GroupBox Header="Title" />


回答2:

A groupboxs headerTemplate is a type of DataTemplate. so you should provide a datatemplate object insteed of style or template.

try below one.

   <Window.Resources>

        <DataTemplate x:Key="DataTemplate1">
            <TextBlock Text="Test Templated Header"/>
        </DataTemplate>

    </Window.Resources>
    <Grid>
        <GroupBox  Header="Test Header" HeaderTemplate="{StaticResource DataTemplate1}">
            <Border BorderBrush="Red" Margin="10">
                <TextBlock Text="Hello"/>
            </Border>
        </GroupBox>
    </Grid>