【问题标题】:inherit style from default style从默认样式继承样式
【发布时间】:2012-07-20 14:34:58
【问题描述】:

在我的项目中,文本框有一个自定义样式。定义为:

<Style TargetType="TextBox"/>

所以它默认应用于所有文本框子控件。

我需要创建另一种基于默认样式的样式。但是如何在 BasedOn 属性中指定我的新样式应该使用默认样式?

【问题讨论】:

    标签: wpf xaml styling


    【解决方案1】:

    使用你想扩展的控件类型

    BasedOn="{StaticResource {x:Type TextBox}}"
    

    完整示例:

    <Style x:Key="NamedStyle" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
        <Setter property="Opacity" value="0.5" />
    </Style>
    

    【讨论】:

    • 如果您想自动应用其他更改(在您的情况下为不透明度)(不带样式名称),则无需设置 x:Key。
    • @honzakuzel1989 确实如此。是否要设置密钥取决于用例。
    • 在 uwp 中怎么样,x:Type 不存在?
    • 谢谢。如果样式适用于某些继承的控件类,例如MyButton : Button,该怎么办? x:Type 在这里会有所帮助,但现在,我假设它必须在自定义类的代码隐藏中完成?
    • 我在想这样的东西可以在ctor中使用:this.DefaultStyleKey = typeof(Button); 然后可以按照通常的方式定义样式。我试试看。
    【解决方案2】:

    @Aphelion 有正确答案。我想补充一下ResourceDictionary事项中定义项目的顺序。

    如果你覆盖了一个滑块的默认样式,并且你想要基于它的另一个滑块样式,你必须在覆盖样式之后声明“基于”滑块。

    例如,如果你这样做:

    <Style x:Key="BlueSlider" TargetType="{x:Type Slider}" BasedOn="{StaticResource {x:Type Slider}}">
        <Setter Property="Background" Value="Blue"/>
    </Style>
    
    <Style TargetType="{x:Type Slider}">
        <Setter Property="Foreground" Value="Yellow"/>
    </Style>
    

    BlueSlider 将具有蓝色背景和默认(白色)前景。

    但如果你这样做:

    <Style TargetType="{x:Type Slider}">
        <Setter Property="Foreground" Value="Yellow"/>
    </Style>
    
    <Style x:Key="BlueSlider" TargetType="{x:Type Slider}" BasedOn="{StaticResource {x:Type Slider}}">
        <Setter Property="Background" Value="Blue"/>
    </Style>
    

    BlueSlider 将具有蓝色背景和黄色前景。

    【讨论】:

      猜你喜欢
      • 2011-07-15
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2013-05-26
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多