Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inherit style from default style

Tags:

styling

wpf

xaml

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?

like image 661
Bogdan Verbenets Avatar asked Jul 20 '12 14:07

Bogdan Verbenets


2 Answers

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> 
like image 180
Myrtle Avatar answered Sep 28 '22 03:09

Myrtle


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

like image 31
Peter Boone Avatar answered Sep 28 '22 03:09

Peter Boone