inherit style from default style
Solution 1
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>
Solution 2
@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.
Bogdan Verbenets
Updated on July 09, 2022Comments
-
Bogdan Verbenets almost 2 years
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?
-
honzakuzel1989 about 8 yearsYou needn't set x:Key if you want apply additional changes (opacity in your case) automatically (without style name).
-
Myrtle about 8 years@honzakuzel1989 that's true indeed. It depends on the use case whether you want the key to be set.
-
bunkerdive over 7 yearsHow about in uwp, where x:Type does not exist?
-
bunkerdive over 7 yearsThanks. What if the style is for some inherited control class, like
MyButton : Button
? Thex:Type
would be helpful here, but now, I'm assuming it must be done in the code-behind for the custom class? -
bunkerdive over 7 yearsI'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.