43

In my project there is a custom style for text box. It is defined as:

<Style TargetType="TextBox"/>

So it is applied to all text box child controls by default.

I need to create another style that is based on default style. But how do I specify in the BasedOn attribute that my new style should use the default style?

Bogdan Verbenets
  • 25,686
  • 13
  • 66
  • 119

2 Answers2

88

Use the type of the control you would like to extend

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

Full example:

<Style x:Key="NamedStyle" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter property="Opacity" value="0.5" />
</Style>
Myrtle
  • 5,761
  • 33
  • 47
  • You needn't set x:Key if you want apply additional changes (opacity in your case) automatically (without style name). – honzakuzel1989 Apr 19 '16 at 11:19
  • 1
    @honzakuzel1989 that's true indeed. It depends on the use case whether you want the key to be set. – Myrtle Apr 20 '16 at 06:55
  • How about in uwp, where x:Type does not exist? – bunkerdive Nov 04 '16 at 15:10
  • Thanks. What if the style is for some inherited control class, like `MyButton : Button`? The `x:Type` would be helpful here, but now, I'm assuming it must be done in the code-behind for the custom class? – bunkerdive Nov 04 '16 at 15:31
  • I'm thinking something like this can be used in the ctor: `this.DefaultStyleKey = typeof(Button);` And then the style can be defined per usual. I'll give it a try. – bunkerdive Nov 04 '16 at 15:33
1

@Aphelion has the correct answer. I would like to add that the order in which items are defined in the ResourceDictionary matter.

If you override the default style of a slider and you want to base another slider style on that, you must declare the "based on" slider after the override style.

For example, if you do this:

<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 will have a blue background with the default (white) foreground.

But if you do this:

<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 will have a blue background and a yellow foreground.

Peter Boone
  • 1,193
  • 1
  • 12
  • 20