lumberjack4
lumberjack4

Reputation: 2872

Problem with StringFormat

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.

Upvotes: 4

Views: 2370

Answers (2)

Eduardo Hern&#225;ndez
Eduardo Hern&#225;ndez

Reputation: 403

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.

Upvotes: 1

Bob Vale
Bob Vale

Reputation: 18474

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>

Upvotes: 5

Related Questions