Styles in WPF are used for controlling the look and feel of the controls across the entire application.This is useful if we want the application to have a consistent look and feel.If we have many textboxes in our application then they should have a similar appearance otherwise the application will not look consistent.
Styles allows us to share the properties and values of the controls so that we can easily change the properties of these controls.Style contains a list of properties and values which can be applied to multiple UI elements.
Styles in WPF are defined by using the <Style> element.Style defines 2 useful properties which we can use when working with Styles:
Setters Used for setting property values
TargetType Indicates the type of the control to which we want to apply the Style.
Setter property is always used when working with Styles ,we can omit the TargetType property which is useful in certain scenarios.
Setting TargetType property
If we have TextBox controls in our application then for giving them consistent look we can define a Style.We can define the font related properties in a Style as:
<Style TargetType="TextBox" x:Key="TextStyle"> <Setter Property="FontSize" Value="12"/> <Setter Property="Font-Color" Value="Black"/> </Style>
We can apply the above Style to a TextBox control as:
<TextBox Style="{StaticResource TextStyle}"></TextBlock>
Applying Style to all the Controls
If we have 50 textboxes in our application then we need to search and individually change the Styles of individual controls.One way to automatically apply the Style to all the TextBox controls in the application is by omitting the x:Key property.
In the below style we are not setting the x:key property ,this will cause the style to be applied to all the TextBox controls.
<Style TargetType="TextBox"> <Setter Property="FontSize" Value="12"/> <Setter Property="Font-Color" Value="Black"/> </Style>
Scope
Style can be applied to the controls depending on where we define the style.For example if we define the style in the Resources element of the Windows element then the style can be applied to all the TextBoxes in the Window while if we define the style in the Grid then the Style will be applied to all the TextBoxes in the Grid.
In the below example we have defined a Style in the Resources element of the Grid ,this will cause the Style to be applied to the TextBoxes inside the Grid.
<Grid.Resources> <Style TargetType="TextBox"> <Setter Property="FontSize" Value="24" /> </Style> </Grid.Resources>
Leave a Reply