【问题标题】:WPF : How to inherit from a base(or default) style in an ItemContainerStyleWPF:如何从 ItemContainerStyle 中的基本(或默认)样式继承
【发布时间】:2013-05-26 00:26:33
【问题描述】:

我在继承 TabControl 的 ItemContainerStyle 中的默认样式时遇到问题。

旨在继承主题风格,只改变一些属性。

如果我编写此 XAML 代码,则使用默认的 TabItem 样式,但不使用主题样式。 你知道为什么吗?

<TabControl>

    <TabControl.Resources>
        <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
            <Setter Property="Background" Value="DarkBlue"/>
        </Style>
    </TabControl.Resources>

    <TabControl.ItemContainerStyle>
        <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
            <Setter Property="Background" Value="Blue"/>
            <Setter Property="Foreground" Value="Red"/>
        </Style>
    </TabControl.ItemContainerStyle>

    <TabItem Header="Tab 1"/>
    <TabItem Header="Tab 2"/>
    <TabItem Header="Tab 3"/>
    <TabItem Header="Tab 4"/>

</TabControl>

PS:对资源中的按钮做同样的事情,效果很好。为什么它没有 TabItem 样式?与 ItemContainerStyle 有什么关系?

PS2 : 我的主题样式(默认样式)存储在应用程序资源中。

谢谢

编辑 1

您可以在我的 Dropbox 上找到示例项目: https://dl.dropboxusercontent.com/u/61987557/InheritDefaultStyle.zip

【问题讨论】:

  • 我试过这段代码,似乎工作正常。按钮和选项卡项都从 App.xaml 中获取了基本样式。您还有其他具体问题吗?
  • 您好 XAML 爱好者,我尝试仅将此代码放入应用程序中,而我的 TabItem 的默认样式直接包含在 App.xaml 中,但它仍然不起作用。我会把源上传给你

标签: wpf styles inheritance itemcontainerstyle


【解决方案1】:

我猜 TabItemStyle 和 ItemContainerStyle 是两个不同的东西 ItemContainerStyle 应用于为每个项目生成的容器元素。 而您正在尝试在 ItemContainerStyle 中设置 TabItemStyle。

【讨论】:

  • 没错,但这就是这样做的方式,不是吗?我想在一个库中为我的 TabItem 设置一个默认样式,但是这个库的用户应该能够更改一些属性,如背景,而不必重写整个样式。你会采取不同的方式吗?
【解决方案2】:

为您的 TabItem 的样式定义一个键:

<Style TargetType="{x:Type TabItem}" x:Key="StandardTabItemControl">
...
</Style>

然后用这个键继承它:

<TabControl.ItemContainerStyle>
   <Style TargetType="TabItem" BasedOn="{StaticResource StandardTabItemControl}">
         ...
   </Style>
</TabControl.ItemContainerStyle>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-15
    • 2013-07-17
    • 1970-01-01
    • 2016-12-14
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多