Search code examples
c#wpftabcontrol

How do I automatically expand my WPF tabitem to fit the header text?


enter image description here

Basically, this is what it looks like, I want my tabitem to automatically make the header text fit inside the tabitem. Thanks.


Solution

  • WPF tabitem widths are adaptive unless you specify a width. If you don't specify a width, check if you have fixed the width of the content control or container when you define the TabItem style.

    <TabControl>
                <TabItem Header="long"/>
                <TabItem Header="longlonglonglong"/>
    </TabControl>
    

    enter image description here

    Initial control template

    <ControlTemplate TargetType="{x:Type TabItem}">
         <Grid x:Name="templateRoot" SnapsToDevicePixels="true">
             <Border x:Name="mainBorder" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" Margin="0">
                 <Border x:Name="innerBorder" Background="{StaticResource TabItem.Selected.Background}" BorderBrush="{StaticResource TabItem.Selected.Border}" BorderThickness="1" Margin="-1" Opacity="0"/>
             </Border>
             <ContentPresenter x:Name="contentPresenter" ContentSource="Header" Focusable="False" HorizontalAlignment="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
          </Grid>
    </ControlTemplate>