是否可以在边框上方显示 GroupBox 的 header?

Is it possible to display the header of a GroupBox above the Border?

是否可以将GroupBox的header显示在边框上方而不是边框​​中?

<GroupBox>
 <GroupBox.Header>
  <TextBlock 
   Text="Test">    
  </TextBlock>
 </GroupBox.Header>
</GroupBox>

您必须编辑 GroupBox 的控件模板并进行调整。您可以使用 Visual Studio or Blend 提取默认控件模板。它包含一个不透明蒙版,为组框边框中的 header 文本创建间隙。您必须删除此边框并像这样移动 header:

<Style x:Key="GroupBoxStyle" TargetType="{x:Type GroupBox}">
   <Setter Property="BorderBrush" Value="#D5DFE5"/>
   <Setter Property="BorderThickness" Value="1"/>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type GroupBox}">
            <Grid SnapsToDevicePixels="true">
               <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="6"/>
                  <ColumnDefinition Width="Auto"/>
                  <ColumnDefinition Width="*"/>
                  <ColumnDefinition Width="6"/>
               </Grid.ColumnDefinitions>
               <Grid.RowDefinitions>
                  <RowDefinition Height="Auto"/>
                  <RowDefinition Height="Auto"/>
                  <RowDefinition Height="*"/>
                  <RowDefinition Height="6"/>
               </Grid.RowDefinitions>
               <Border Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="Transparent" CornerRadius="4" Grid.ColumnSpan="4" Grid.Column="0" Grid.RowSpan="3" Grid.Row="1"/>
               <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="White" CornerRadius="4" Grid.ColumnSpan="4" Grid.RowSpan="3" Grid.Row="1">
                  <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="3">
                     <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="White" CornerRadius="2"/>
                  </Border>
               </Border>
               <Border x:Name="Header" Grid.Column="1" Padding="3,1,3,0" Grid.Row="0">
                  <ContentPresenter ContentSource="Header" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
               </Border>
               <ContentPresenter Grid.ColumnSpan="2" Grid.Column="1" Margin="{TemplateBinding Padding}" Grid.Row="2" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
            </Grid>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

然后你可以像这样在你的 XAML 中使用样式来应用控件模板:

<GroupBox Style="{StaticResource GroupBoxStyle}" Header="Test">
   <!-- ...your content. -->
</GroupBox>

或者将组框样式定义为隐式样式以自动将其应用于所有 GroupBoxes。

<Style TargetType="{x:Type GroupBox}">
   <!-- ...same as above. -->
</Style>