What is Style in WPF ?

As the name tells it is a way to customize or personalize the look or appearance of objects. A style is a collection of values which represents properties of a specified control. We can assign certain set of styles collectively for a specific type of control ( like all buttons, all textboxes etc) or restrict the style to be used only by those controls which you want explicitly with the help of keys(x:key).

Styles are typically defined as resources in XAML.




Apply style to all controls of same type.

<Window.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Orange" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Height" Value="50" />
<Setter Property="Width" Value="200" />
</Style>
</Window.Resources>
<Grid>
<Button Margin="10,53,307,216">Button1</Button>
<Button Margin="261,53,56,216">Button2</Button>
<Button Margin="142,156,175,113">Button3</Button>
</Grid>

In the above code we are specifying target type = Button and not providing any key to this style. So all the Buttons of the page will get this style applied automatically.

Corresponding images:
XAML
Style
Output

Applying Style to a particular control using Key

<Window.Resources>
<Style x:Key="btnStyle" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Orange" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Height" Value="50" />
<Setter Property="Width" Value="200" />
</Style>
</Window.Resources>
<Grid>
<Button Style = "{StaticResource btnStyle}" Margin="37,34,280,235">seekyourcareer.in</Button>
<Button Style = "{StaticResource btnStyle}" Margin="37,144,280,125">seekyourcareer.in</Button>
<Button Height="50" Width="150" Margin="167,141,200,128">Style not applied</Button>
</Grid>

Corresponding Images
XAML
Style

Output
Style
So you can see above that style is not applied to third button because we did not give the key to it.

Note :

‘TargetType’ define the type of target the style is going to hit. If you are not specifying it, you must qualify the property with classname explicitly (Button / Textblock).

Syntax : <Setter Button.Property =”Background” Value =”Orange” />

Tip:

Always use x:key and explicitly provide style to the controls. Reason : Suppose you are applying common style to all the textblock in your application. And You have a ListBox which consists of a textblock as its part. Then the style is also applied to this textblock. and you might get unexpected results.