Styles in WPF

WPF styles works just like CSS style, In the CSS we define styles for a control and we reuse the same where ever we need in the application, same way the styles in WPF allows to define the properties and can be reuse in the application. Here we may have a question like we had a concept called resources in WPF then why it needs another concept called styles in order to do the same work. The answer for your question is that a resource is used to target the properties of more than one type of control where as style can define properties only for a single type of control at a time. And also we can define different styles as a part of one common resource.

Styles have a set of properties; here I am going to place some of important and frequent used properties.

Setters: Sets the property values
Triggers: Change the style settings
Resources: Gets or Sets a collection of resources you can use
BasedOn: Creates a specialized style that inherits the settings of another style
TargetType: Gets or Sets the Control for which the style is intended

Let's have a basic example of this, shall we?

Copy and paste the below code in your window1.xaml

  1. <Window.Resources>  
  2.         <Style x:Key="wpfStyle1" TargetType="{x:Type TextBlock}">  
  3.             <Setter Property="FontFamily" Value="Verdana"/>  
  4.             <Setter Property="FontSize" Value="10"/>  
  5.         </Style>  
  6.         <Style x:Key="wpfStyle2" TargetType="{x:Type TextBlock}">  
  7.             <Setter Property="FontFamily" Value="Arial"/>  
  8.             <Setter Property="FontSize" Value="16"/>  
  9.         </Style>  
  10. </Window.Resources>  
  11.     
  12. <Grid>  
  13.         <TextBlock Margin="26,41,39,0" Style="{StaticResource wpfStyle1}" Height="31" VerticalAlignment="Top">TextBlock with Style1</TextBlock>  
  14.         <TextBlock Margin="26,77,39,0" Height="32" VerticalAlignment="Top">TextBlock with no Style</TextBlock>  
  15.         <TextBlock Margin="26,113,67,88" Style="{StaticResource wpfStyle2}">TextBlock with Style2</TextBlock>   
  16. </Grid>  

The code seen above creates a Style in the <Window.Resources>. That Style targets elements of type TextBlock, and sets their FontFamily and FontSize properties. Notice that the Styles have keys named wpfStyle1, wpfStyle2. The Style property on each TextBlock is then explicitly set to reference that Style.

Conclusion

This article would help you understand the styles in WPF.

Up Next
    Ebook Download
    View all
    Learn
    View all