从默认样式继承样式



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

<Style TargetType="TextBox"/>

因此,默认情况下,它应用于所有文本框子控件。

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

使用要扩展的控件类型

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

完整示例:

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

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

CCD_ 3将具有蓝色背景和黄色前景。

最新更新