WPF: apply style only to one tabcontrol containing other tabControl

大憨熊 提交于 2019-12-24 12:43:46

问题


In my wpf application, I have a tabControl (parent) that contains another tabcontrol (child). I would like to apply a style to the tabItem of the parent tabControl without affecting the child one. I tried with this:

<TabControl x:Name="Parent" TabStripPlacement="Left" 
            ItemsSource="{Binding Path=ParentTabItems, Mode=OneWay}" >
    <TabControl.Resources>
        <Style TargetType="{x:Type TabItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TabItem}">
                        <!-- template is defined here-->
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="{x:Type TabPanel}">
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
    </TabControl.Resources>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <ContentPresenter>
                <ContentPresenter.Content>
                    <!--Here there is the child TabControl-->
                </ContentPresenter.Content>
            </ContentPresenter>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

But this results in applying the style also to the child tabControl TabItem. How can I apply the style only to the parent tabItem leaving the child TabControl using the default style defined in the application?


回答1:


You should be able to use the TabControl.ItemContainerStyle to set a named Style on the TabItems of the outer TabControl. Try this:

In Resources:

<Style x:Key="ItemStyle" TargetType="{x:Type TabItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TabItem}">
                <!-- template is defined here-->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

...

<TabControl x:Name="Parent" TabStripPlacement="Left" 
    ItemsSource="{Binding Path=ParentTabItems, Mode=OneWay}" 
    ItemContainerStyle="{StaticResource ItemStyle}">
    <TabControl.Resources>
        <Style TargetType="{x:Type TabPanel}">
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
    </TabControl.Resources>
</TabControl>


来源:https://stackoverflow.com/questions/28945115/wpf-apply-style-only-to-one-tabcontrol-containing-other-tabcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!