Reader Level:
ARTICLE

Styles in WPF

Posted by Anil Veeragandham Articles | WPF August 10, 2009
This article explains basics of styles in WPF.
  • 0
  • 0
  • 21819


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


<
Window.Resources>

        <Style x:Key="wpfStyle1" TargetType="{x:Type TextBlock}">

            <Setter Property="FontFamily" Value="Verdana"/>

            <Setter Property="FontSize" Value="10"/>

        </Style>

        <Style x:Key="wpfStyle2" TargetType="{x:Type TextBlock}">

            <Setter Property="FontFamily" Value="Arial"/>

            <Setter Property="FontSize" Value="16"/>

        </Style>

</Window.Resources>

  

<Grid>

        <TextBlock Margin="26,41,39,0" Style="{StaticResource wpfStyle1}" Height="31" VerticalAlignment="Top">TextBlock with Style1</TextBlock>

        <TextBlock Margin="26,77,39,0" Height="32" VerticalAlignment="Top">TextBlock with no Style</TextBlock>

        <TextBlock Margin="26,113,67,88" Style="{StaticResource wpfStyle2}">TextBlock with Style2</TextBlock>
</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.

COMMENT USING

Trending up