WPF Basics - Styles
Styles are a means to define a common look and feel to controls. They are similar to CSS stylesheets for web pages, but are defined using XAML syntax. Styles are typically defined in the Resources section of a control, panel, or the parent window. They can also be collected into what are known as ResourceDictionaries, and hosted in external files.
To implement a style, follow these step
- Create a <style> within a Resources collection and give it a key
- Create <setter> elements within the style to set properties to specific values
- Use the style from an element using the Style attribute
For example, here is a demo which defines two styles as part of a Canvas' resources collection. The styles changes the default
display of buttons to be 25x100, with a black background and white text. The named style is derived from the first style (style inheritance)
and sets the background of the button to DarkBlue instead. The third button references the named style via the Style attribute.
<Canvas>
<Canvas.Resources>
<!-- No x:Key specified, so this becomes the default for buttons -->
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Black" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Height" Value="25" />
<Setter Property="Width" Value="100" />
</Style>
<!-- A style with a key must be referenced explicitly using the Style attribute -->
<!-- Note also that the BasedOn attribute can be used for style inheritance -->
<Style x:Key="SpecificStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Background" Value="DarkBlue" />
</Style>
</Canvas.Resources>
<Button Canvas.Left="10" Canvas.Top="10">Button 1</Button>
<Button Canvas.Left="10" Canvas.Top="44">Button 2</Button>
<Button Style="{StaticResource SpecificStyle}" Canvas.Left="10" Canvas.Top="77">Button 3</Button>
</Canvas>
Effects of TargetType and Key
When creating a style, including or omitting the TargetType and Key has the following effects:
- TargetType only - style is automatically applied as the default for all elements of that type within scope
- Key only - style can be applied to different elements. Properties not on the element are ignored. The Setter properties
must include "Control." (eg. Property="Control.Background")
- Key and TargetType - style can be applied to the target type via explicit use of the Style attribute on the element