Thursday, August 7, 2008

WPF Styles BasedOn keyless resource

This post isn't so much to share any new found glory on WPF as it is a note to myself. I can never remember the syntax of basing a WPF style upon the existing default style.

For example I may want to create a default style for all of my buttons to have a background of "AliceBlue"

<Style TargetType="Button">
  <Setter value="AliceBlue" property="Background" />

If I create another style it will not automatically pick up the default styles set above.

<Style TargetType="Button" x:Key="NewButtonStyle">
  <Setter value="Red" property="Foreground" />

The fix is to specify the type as the resource key for the BasedOn property.

<Style TargetType="Button" x:Key="OverrideButtonStyle" BasedOn="{StaticResource {x:Type Button}}">
  <Setter value="Red" property="Foreground" />

Notice that the middle button wont get the blue background

  <Button Style="{StaticResource NewButtonStyle}">New</Button>
  <Button Style="{StaticResource OverrideButtonStyle}">Override</Button>

Nothing new here!


Anonymous said...

Why don't you have curly brackets and x:Type around Button?

Lee Campbell said...

Because I am lazy! Off the top of my head I believe that a TypeConverter will be activated here and convert my string to the Button Type

Thorsten Lorenz said...

Thank you very much for this little gem of information.
It comes in very handy, when basing styles on generic styles defined in themes (e.g. WPFThemes (codeplex)).

Surender Jain said...

Thanks a lot. This is exactly what I was looking for.

Karel said...

Small article, great help. Thanks!

Anonymous said...

Nice one :-D

Richard said...

Is there a way to base a style on the generic style found in the generic.xaml file? Essentially jumping over the default style to the generic style.

Lee Campbell said...

The same technique will work for keyless styles that have been defined by you (in your Generic.xaml or any other in-scope resource dictionary).