问题
I have a TabControl with a style that changes the FontSize of the Header of the TabItem. When I data bind the ItemsSource only the headers are affected by the FontSize. But when I use the same style on another TabControl and add the TabItems in XAML the FontSize is changed on all content in the TabItem. I want the style to work with both databound and non-databound TabItems.
<TabControl Style="{StaticResource VariablesTabControl}" ItemsSource="{Binding TabItems}">
...
</TabControl>
MainSkin.xaml:
<Style TargetType="TabControl" x:Key="VariablesTabControl">
<Setter Property="ItemContainerStyle" Value="{StaticResource VariableTabItem}" />
...
</Style>
<Style TargetType="TabItem" x:Key="VariableTabItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<Grid Name="Panel" MinHeight="30" MinWidth="120">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center" HorizontalAlignment="Left" ContentSource="Header" Margin="10,2" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="False">
<Setter TargetName="Panel" Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="{StaticResource ForegroundBrush}" />
<Setter Property="FontSize" Value="12" />
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="Panel" Property="Background" Value="{StaticResource BackgroundMouseOver}" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="Panel" Property="Background" Value="{StaticResource SelectedBrush}" />
<Setter Property="Foreground" Value="{StaticResource ForegroundBrush}" />
<Setter Property="FontSize" Value="12" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
回答1:
Your problem is a result of Property Value Inheritance.
When you define the TabItem
s in xaml something like this:
<TabItem>
<TabItem.Header>
<TextBlock Text="TEST_HEADER1" />
</TabItem.Header>
<TextBlock Text="TEST_CONTENT1" />
</TabItem>
Both TextBox
es, the header, and the content are in the logical tree of the TabItem
that means that any Inheritable property set on TabItem
will be propagated down the tree to these TextBox
es.
The Foreground
and FontSize
are Inheritable.
If you have something like:
<TabItem Header="TEST_HEADER2">TEST_CONTENT2</TabItem>
you don't have any Elements in TabItem
's logical tree, the elements for the Header and the content will be auto generated, and the properties will not be inherited.
But this type of declaring TabItem
's is not very useful, you usually need some advanced XAML as the items content so I think the best way to solve this is by changing all those text properties in TabItem
's HeaderTemplate
, you can bind to TabItem's
properties using the RelativeSource
.
来源:https://stackoverflow.com/questions/25844105/how-do-i-set-tabcontrols-tabitem-header-fontsize