Search code examples
c#wpfxamlheadertabitem

How to center header texts on TabItems


I'm trying to get my WPF TabItems to center their header texts. But no matter which combinations of HorizontalAlignment and HorizontalAlignment (center or stretch) I set on the ContentPresenter and its containing Border, the text always appears aligned to the left, rather than centered. I also don't see a Property on TabItems that I could use to set this directly on the tab items themselves (as it turns out, HorizontalAlignment on a TabItem does something completely different).

My code right now is this:

<Grid TextElement.Foreground="White" TextElement.FontSize="17" TextElement.FontFamily="Times New Roman" HorizontalAlignment="Center" >
   <Border Name="TabBorder" BorderThickness="8 8 8 0"  CornerRadius="12 12 0 0"  
           Background="{StaticResource bandBrush}" HorizontalAlignment="Center" >
   <ContentPresenter HorizontalAlignment="Stretch" ContentSource="Header" Height="24" Width="100" />
   </Border>
 </Grid>

Solution

  • You could put the ContentPresenter in a Label with the HorizontalAlignment property set to Strecth and the HorizontalContentAlignment set to Center, Check out this:

    <Grid x:Name="gridTabItem">
      <Border x:Name="Border" Margin="0,0,0,0" BorderBrush="{x:Null}" CornerRadius="7,7,0,0" BorderThickness="0" >
        <Label  x:Name="label" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center">
          <ContentPresenter x:Name="ContentSite"
                          VerticalAlignment="Stretch"  
                     HorizontalAlignment="Center"
                     ContentSource="Header" Margin="10,2,10,2"
                     RecognizesAccessKey="True">
          </ContentPresenter>
        </Label>
    
      </Border>
      <Rectangle x:Name="rectangle" HorizontalAlignment="Left" Height="4" Margin="0,41, 0,0" Stroke="{x:Null}" VerticalAlignment="Top" Width="{Binding ActualWidth, ElementName=gridTabItem}" StrokeThickness="0" Fill="{x:Null}"/>
      <Rectangle x:Name="rectangle1" HorizontalAlignment="Left" Height="1" Margin="0,43,0,0" Stroke="{x:Null}" StrokeThickness="0" VerticalAlignment="Top" Width="{Binding ActualWidth, ElementName=gridTabItem}" Fill="#FFEEEEEE"/>
      <Rectangle x:Name="glow" HorizontalAlignment="Left" Height="41" Margin="0" Stroke="{x:Null}" StrokeThickness="0" VerticalAlignment="Top" Width="{Binding ActualWidth, ElementName=gridTabItem}" Fill="{x:Null}"/>
    </Grid>