wpfStyles in WPF


Remarks

Introductory remarks

In WPF, a Style defines the values of one or more dependency properties for a given visual element. Styles are used throughout the application to make the user interface more consistent (e.g. giving all dialog buttons a consistent size) and to make bulk changes easier (e.g. changing the width of all buttons.)

Styles are typically defined in a ResourceDictionary at a high level in the application (e.g. in App.xaml or in a theme) so it is available app-wide, but they may also be defined for a single element and its children, e.g. applying a style to all TextBlock elements inside a StackPanel.

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Margin" Value="5,5,5,0"/>
            <Setter Property="Background" Value="#FFF0F0F0"/>
            <Setter Property="Padding" Value="5"/>
        </Style>
    </StackPanel.Resources>
        
    <TextBlock Text="First Child"/>
    <TextBlock Text="Second Child"/>
    <TextBlock Text="Third Child"/>      
</StackPanel>

Important notes

  • The location where the style is defined affects where it is available.
  • Forward references cannot be resolved by StaticResource. In other words, if you're defining a style that depends upon another style or resource in a resource dictionary, it must be defined after/below the resource upon which it depends.
  • StaticResource is the recommended way to reference styles and other resources (for performance and behavioral reasons) unless you specifically require the use of DynamicResource, e.g. for themes that can be changed at runtime.

Resources

MSDN has thorough articles on styles and resources that have more depth than is possible to provide here.