Silverlight how-to: Inherit from an Implicit Style

Silverlight 4Since Silverlight 4 you can use Implicit Styles:
http://weblogs.asp.net/lduveau/archive/2009/11/18/silverlight-4-implicit-styling.aspx

Basically it is just a style defined in resource without a key. As you don’t have a key you may wonder how you could inherit (BasedOn) from an implicit style?

Surprisingly lots of people are not aware of this, so here is how you can inherit from an implicit style:

 

1. Add a key to your implicit style (so it won’t be implicit anymore… but wait)

Microsoft use this technique in the Silverlight Toolkit, and their naming convention is DefaultXXXStyle.

So for a Button you would create DefaultButtonStyle like this sample:

<Style TargetType="Button" x:Key="DefaultButtonStyle">
    <Setter Property="Background" Value="BlueViolet"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="FontFamily" Value="Verdana"/>
    <Setter Property="FontSize" Value="11"/>
    <Setter Property="FontWeight" Value="SemiBold"/>
</Style>

2. Create a new Implicit Style based on this style:

<Style TargetType="Button" BasedOn="{StaticResource DefaultButtonStyle}" />

Now all your button will take DefaultButtonStyle as their implicit style.

 

3. The beauty is you can now create other Styles also based on DefaultButtonStyle, which make your new Styles inherit from the “Implicit Style”!

<Style TargetType="Button" x:Key="BigButtonStyle" BasedOn="{StaticResource DefaultButtonStyle}">
    <Setter Property="FontFamily" Value="Arial Black"/>
    <Setter Property="FontSize" Value="32"/>
</Style>

 

<Style TargetType="Button" x:Key="BigRedButtonStyle" BasedOn="{StaticResource BigButtonStyle}">
    <Setter Property="Foreground" Value="Red"/>
</Style>

 

Which gives me this Styles hierarchy:

Silverlight inheriting from implicit style

Easy.

3 Comments

  • this is misleading. as you are not actually inheriting from the implicit style (which cannot be done). what you've done is define an explicit style "DefaultButtonStyle" that your implicit and all other styles inherit from it.

  • Hey Laurent,

    just wanted to thank you for this post, I had problems with the implicit TextBlock style foreground colour taking precedence over the one coming from the ContentControl, but having a base style without foreground colour, basing the implicit style on that and explicitly setting the base style on my TextBlock made it possible to inherit from ContentControl! :)

    Cheers,
    Daniel

  • @Shemesh: True, technically, we do not inherit from the Implicit Style...

Comments have been disabled for this content.