#9 – Styles

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"/>
Advertisements