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

时间:2016-06-01 08:36:41

标签: wpf xaml tabcontrol wpf-style

我在开头定义了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,我不会在那里应用父标签的样式。

解决方案是什么?

2 个答案:

答案 0 :(得分:2)

您的问题:

  

问题是你的风格没有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>

enter image description here

解决方案:

  

避免将Style应用于相同类型的所有控件   在TargetType中定义,您需要提供ResouceKey

     

要使用x:Key应用样式,您现在需要在要使用它的控件的Style属性中指定它。

     

这是通过以下方式完成的: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>

这仅适用于您设置样式的StyleTabItem

StyleApplied

答案 1 :(得分:2)

如下面的代码:

<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>

<强> 输出:

output