Silverlight provides a great set of controls, with which you can capture and display data. While the properties for the controls can be assigned directly to each control, in our .XAML file using attributes, some properties can be duplicated among different controls, causing difficulties in our .XAML maintenance.
Here is an example of this issue.
<Button x:Name=”btnSubmit” FontFamily=”Arial”
FontWeight=”Bold” Width=”100″ Height=”25″ Margin=”10″ />
<Button x:Name=”btnCancel” FontFamily=”Arial”
FontWeight=”Bold” Width=”100″ Height=”25″
Margin=”10″ />
You can see that both controls define the same value for FontFamily, FontWeight, Width, Height and Margin. Maybe this XAML works correctly, but for better common properties control, we must encapsulate repetitive properties within reusable “Styles”, with this you are able to apply common properties to any button, easy and fast. The control “Styles” can be housed in the Application. Resources element. The Styles are defined using the Style element, for example:
<Style x:Key=”ButtonStyle” TargetType=”Button”>
</Style>
In this example I defined a Style using a key (¨x:key¨) called “ButtonStyle” this style can only be applied to Button controls by the TargetType.
This example also shows how to assign control repetitive properties in a reusable Style.
<Style x:Key=”ButtonStyle” TargetType=”Button”>
<Setter Property=”FontFamily” Value=”Arial” />
<Setter Property=”FontWeight” Value=”Bold” />
<Setter Property=”Width” Value=”100″ />
<Setter Property=”Height” Value=”25″ />
<Setter Property=”Margin” Value=”5,10,0,10″ />
</Style>
Last here is how to assign this style to our button
<Button x:Name=”btTestStyle” Content=”Test Button” Style=”{StaticResource ButtonStyle}”/>
Stay tuned for more Silverlight posts!