#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"/>
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #9 – Styles

  1. Pingback: #158 – When to Create a Custom Dependency Property « 2,000 Things You Should Know About WPF

  2. Pingback: #267 – Think Twice Before You Subclass a Control « 2,000 Things You Should Know About WPF

  3. Ivan says:

    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:

    • Sean says:

      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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: