Silverlight Tip of the Day #55 – How to Apply Styles in Silverlight – Part I
Styles are extremely important because they allow developers to control the look and layout of controls across their application. By using styles you can simply change the style declaration and all controls in the application are updated automatically. This is a much faster alternative to updating each and every control in your application individually.
For this tip we will be exploring the basic fundamental use of styles in Silverlight. I will follow up with more complex scenarios in the next Tip of the Day.
In Silverlight, styles are declared within the controls <UserControl.Resources> tags. If you want to make them global to all controls you can put them in your App.XAML file within the <Application.Resources> tags.
To illustrate this point let’s create a global style on how we will display TextBlocks throughout our sample application:
<Application xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
x:Class="MyApp.App">
<Application.Resources>
<Style x:Name="TextBoxStyle" TargetType="TextBlock">
<Setter Property="FontFamily" Value="Calibri.ttf#Calibri"></Setter>
<Setter Property="FontSize" Value="16"></Setter>
</Style>
</Application.Resources>
</Application>
For the XAML above:
- Style - Declare each style within <Style></Style>tags in the <Application.Resources> or <UserControl.Resources> section.
- Name – Set the name of the style (via x:Name=””) so we can reference it from our controls.
- TargetType -The name of the FrameworkElement you are targeting. In our case above we are targeting a “TextBlock”.
- Setter - Each property we want to set for this style is declared as a Setter. You can set multiple setters per style. For example, FontSize, FontFamily, etc.
Next, the following XAML below shows how to create multiple TextBlocks with the same style applied to it.
<TextBlock x:Name="myTextBlock" Text="Hello There." Style="{StaticResource TextBoxStyle}"></TextBlock>
<TextBlock x:Name="myTextBlock2" Text="How are you?" Style="{StaticResource TextBoxStyle}"></TextBlock>
<TextBlock x:Name="myTextBlock2" Text="Good thanks!" Style="{StaticResource TextBoxStyle}"></TextBlock>
Finally, if we want to change the font size for these TextBlocks all we have to do is change it in the style setter rather than in each individual TextBlock.
Before: <Setter Property="FontSize" Value="16"></Setter>
After: <Setter Property="FontSize" Value="25"></Setter>
Thank you,
--Mike Snow
Subscribe in a reader