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" /> </Style>
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" /> </Style>
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" /> </Style>
Notice that the middle button wont get the blue background
<StackPanel> <Button>Default</Button> <Button Style="{StaticResource NewButtonStyle}">New</Button> <Button Style="{StaticResource OverrideButtonStyle}">Override</Button> </Stackpanel>
Nothing new here!
8 comments:
Why don't you have curly brackets and x:Type around Button?
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
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)).
Thanks a lot. This is exactly what I was looking for.
Small article, great help. Thanks!
Nice one :-D
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.
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).
Post a Comment