如何将 TabControl 样式应用于特定的 tabcontrol?

How to apply TabControl style to a specific tabcontrol?

我有一个 TabControl,开头定义了 TabControl.Resources。这工作得很好,但问题是我在父项 TabControl 中有另一个 TabControl,我不希望将样式应用于子项 TabControl

这是一个例子:

<TabControl>
   <TabControl.Resources>
       some style and triggers
   </TabControl.Resources>
   <TabItem> 
      //Style correctly applied here - there is an external control with a tab item
   </TabItem>
</TabControl>

外部控件是我创建的,我只是将xaml拆分到其他文件中,这个有另一个TabControl,我没有在那里应用父选项卡的样式。

有什么解决办法?

您的问题:

The problem is that your style has no x:Key

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
    xmlns:local="clr-namespace:WpfApplication1"        
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TabControl>
        <TabControl.Resources>
            <Style TargetType="TabItem">
                <Setter Property="Foreground" Value="Red"></Setter>
            </Style>
        </TabControl.Resources>
        <TabItem Header="Tab 01">
            //Style correctly applied 
    here there is an external control with a tab item
        </TabItem>
        <TabItem Header="Tab 02">//Style correctly applied 
    here there is an external control with a tab item
        </TabItem>
    </TabControl>
</Grid>


解决方法:

To avoid a Style from being applied to all Controls of the same type definded in TargetType you need to provide a ResouceKey.

To apply the Style with an x:Key you now need to specify it in the Style property of the control you want to use it on.

This is done with: Style="{StaticResource StyleName}"

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
    xmlns:local="clr-namespace:WpfApplication1"        
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TabControl>
        <TabControl.Resources>
            <Style x:Key="CustomStyle" TargetType="TabItem">
                <Setter Property="Foreground" Value="Red"></Setter>
            </Style>
        </TabControl.Resources>
        <TabItem Header="Tab 01">
            //No Style will be applied
        </TabItem>
        <TabItem Header="Tab 02" Style="{StaticResource CustomStyle}">//Style correctly applied 
    here there is an external control with a tab item
        </TabItem>
    </TabControl>
</Grid>

这只会将 Style 应用到您已设置样式的 TabItem

喜欢下面的代码:

<TabControl>
    <TabControl.Resources>
        <Style TargetType="TabItem" x:Key="tabItemStyle">                
            <Setter Property="Foreground" Value="Red" />
            <Setter Property="Header" Value="Styled Header" />
        </Style>
    </TabControl.Resources>
    <TabItem Style="{StaticResource tabItemStyle}">

    </TabItem>
    <TabItem Header="Simple Header">

    </TabItem>
</TabControl>

输出: