4

I'm trying to use the StringFormat in XAML to populate the Header text on a TabItem. The code I am using is:

<TabControl.ItemContainerStyle>
    <Style TargetType="{x:Type TabItem}" BasedOn="{StaticResource TabItemStyle}">
        <Setter Property="Header" Value="{Binding MyValue, StringFormat='My Value is {0}'}" />
        <EventSetter Event="FrameworkElement.Loaded" Handler="OnTabItemLoaded" />
        <EventSetter Event="FrameworkElement.Unloaded" Handler="OnTabItemUnloaded" />
    </Style>
</TabControl.ItemContainerStyle>

The problem is my header is only showing the value of MyValue in the Header and not the formatted text.

1
  • you should consider setting the HeaderStringFormat answer as the correct one. It's a 15 second fix rather than a 15 minute one. Commented Jul 21, 2023 at 2:10

2 Answers 2

5

Because the Header property is not a string property.

You need to use a headertemplate containing a TextBlock which you can bind the Text property using your stringformat

<TabControl.ItemContainerStyle> 
    <Style TargetType="{x:Type TabItem}" BasedOn="{StaticResource TabItemStyle}"> 
        <Setter Property="HeaderTemplate">
          <Setter.Value>
            <DataTemplate>
              <TextBlock Text="{Binding MyValue, StringFormat='My Value is {0}'}" /> 
            </DataTemplate>
          </Setter.Value>
        </Setter>
        <EventSetter Event="FrameworkElement.Loaded" Handler="OnTabItemLoaded" /> 
        <EventSetter Event="FrameworkElement.Unloaded" Handler="OnTabItemUnloaded" /> 
    </Style> 
</TabControl.ItemContainerStyle>
Sign up to request clarification or add additional context in comments.

2 Comments

I had to change the ControlTemplate to a DataTemplate, but that gave me exactly what I was looking for.
I think nowadays you can simply use HeaderStringFormat, see my answer below.
2

The simplest solution is to use the HeaderStringFormat property:

<Setter Property="Header" Value="{Binding MyValue}" />
<Setter Property="HeaderStringFormat" Value="My Value is {0}" />

WPF seems to follow this pattern whenever you can assign a string to a generic content property, another example would be ContentControl.ContentStringFormat.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.