开发者

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开发者_C百科="{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.


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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜