如何Wpf TabItem样式HeaderTemplate绑定?

时间:2011-09-21 10:15:00

标签: wpf xaml styles tabitem

如何做Wpf TabItem样式HeaderTemplate绑定?

代码:

<TabControl x:Name="tabCtrlMain" ItemsSource="{Binding Items}" >
        <TabControl.Resources>
            <Style TargetType="TabItem">
                <Setter Property="HeaderTemplate">
                    <Setter.Value>
                        <DataTemplate DataType="{x:Type TabItem}">
                            <TextBlock Text="{Binding FileName}"/>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TabControl.Resources>
    </TabControl>

绑定时此代码无效:

<TextBlock Text="{Binding FileName}"/>

2 个答案:

答案 0 :(得分:12)

试试这个,

<TabControl x:Name="tabCtrlMain" ItemsSource="{Binding Items}" >
        <TabControl.Resources>
            <Style TargetType="TabItem">
                <Setter Property="Header" Value="{Binding FileName}" />
                <Setter Property="HeaderTemplate">
                    <Setter.Value>
                        <DataTemplate DataType="{x:Type TabItem}">
                            <Border x:Name="grid">
                                    <ContentPresenter>
                                        <ContentPresenter.Content>
                                            <TextBlock Text="{TemplateBinding Content}"/>
                                        </ContentPresenter.Content>
                                    </ContentPresenter>
                                </Border>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TabControl.Resources>
    </TabControl>

答案 1 :(得分:11)

我知道现在已经非常老了,但我想我只是为了完整性和历史准确性而投入我的两分钱:)

我更喜欢使用ItemContainerStyle做同样的事情,因为它对我来说感觉有点干净,因为它确切地说明了目的:

<TabControl ItemsSource="{Binding Items}">
  <TabControl.ItemContainerStyle>
    <Style TargetType="TabItem">
      <Setter Property="Header" Value="{Binding FileName}" />
      <Setter Property="HeaderTemplate">
        <Setter.Value>
          <DataTemplate>
            <Border>
              <TextBlock Text="{Binding Content}" />
            </Border>
          </DataTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </TabControl.ItemContainerStyle>
</TabControl>

此外,如果唯一的目标是将FileName放入选项卡,那么它可以更简单:

<TabControl ItemsSource="{Binding Items}" DisplayMemberPath="FileName" />