问题
Using the default style
<Style TargetType="{x:Type TabItem}"x:Key="HeaderStyleS">
<Setter Property="Header" Value="{Binding RelativeSource={RelativeSource Self},
Path=Content.DataContext.ViewName}" />
</Style>
It works. But in my case I need to custom the TabItem
So I used
<Style TargetType="{x:Type TabItem}" x:Key="HeaderStyle">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid Background="{TemplateBinding Background}" SnapsToDevicePixels="true" Height="23">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="25"/>
</Grid.ColumnDefinitions>
<ContentPresenter ContentSource="Header" Margin="10,0,10,0" HorizontalAlignment="Center" VerticalAlignment="Center">
<ContentPresenter.Resources>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource Foreground}"/>
<Setter Property="Text" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.DataContext.ViewName}"></Setter>
</Style>
</ContentPresenter.Resources>
</ContentPresenter>
<Button Grid.Column="1" Height="15" Width="15" HorizontalAlignment="Center" VerticalAlignment="Center">
...
</Style>
The problem now is the Header
text is not shown. Any ideas?
回答1:
Try these:
{Binding Path=Content.DataContext.ViewName, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}
or
{Binding Path=DataContext.ViewName, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}
or
{Binding Path=ViewName}
来源:https://stackoverflow.com/questions/27572362/how-to-use-binding-relativesource-in-style