O'Reilly logo

WPF Programmer's Reference: Windows Presentation Foundation with C# 2010 and .NET 4 by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix M. Styles

A Style lets you define a package of properties that you can later assign as a group to make controls more consistent and to make the code easier to read.

You can define Styles in a control's Resources section. If you are going to share a Style, it is most convenient to place it in a container's Resources section.

Typically a Style contains Setter and EventSetter objects that define specific property values and event handlers for the controls that use the Style.

You can make two kinds of Styles: named and unnamed.

Named Styles

To make a named Style, give it an x:Name attribute. Later you can refer to the Style as a StaticResource.

The following XAML code defines and uses a Style named styButton:

<StackPanel Orientation="Horizontal">
    <StackPanel.Resources>
        <Style x:Key="styButton" TargetType="Button">
            <Setter Property="Width" Value="100"/>
            <Setter Property="Height" Value="30"/>
            <Setter Property="Margin" Value="5"/>
            <Setter Property="FontSize" Value="14"/>
            <Setter Property="FontWeight" Value="Bold"/>
            <EventSetter Event="Click" Handler="MenuButton_Clicked"/>
        </Style>
    </StackPanel.Resources>

    <Button Style="{StaticResource styButton}" Content="Customers"
     Width="150"/>
    <Button Style="{StaticResource styButton}" Content="Orders"/>
    <Button Style="{StaticResource styButton}" Content="Inventory"/>
    <Button Content="Maintenance" Width="75" Height="25"
     Click="Maintenance_Clicked"/>
</StackPanel>

The Style defines the Button properties Width, Height, Margin, FontSize, and FontWeight ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required