#9 – Styles
July 21, 2010 4 Comments
In WPF, a style is a set of property values that you can reuse when setting similar properties for a number of controls. You can store a style as a resource and then apply that resource to multiple controls by setting their Style property.
Let’s say that you have a set of properties that you want to apply to several buttons in your UI. You can first define a new style as a static resource:
<Window.Resources> <Style x:Key="StdButton" TargetType="Button"> <Setter Property="Width" Value="100"/> <Setter Property="Control.Background" Value="AliceBlue"/> <Setter Property="Control.FontFamily" Value="Calibri" /> <Setter Property="Control.FontWeight" Value="Bold" /> </Style> </Window.Resources>
Then you can apply this style using the Style property for individual Button controls:
<Button Content="I'm stylish" Style="{StaticResource StdButton}" /> <Button Content="Me Too" Style="{StaticResource StdButton}" /> <Button Content="Not me"/>
Pingback: #158 – When to Create a Custom Dependency Property « 2,000 Things You Should Know About WPF
Pingback: #267 – Think Twice Before You Subclass a Control « 2,000 Things You Should Know About WPF
gives an error
MC4003: Cannot resolve the Style Property ‘Width’. Verify that the owning type is the Style’s TargetType, or use Class.Property syntax to specify the Property.
It should be:
Thanks Ivan. I’ve updated the example to include a TargetType property on the tag. You could have also used a property of “Button.Width” in the Setter.
Interestingly, though the compiler issues an error about the Width property being ambiguous, the WPF designer correctly reads it and applies the style.