Simple Style Definition in Silverlight INFO

Instead of specifying separately for each and every element how exactly it should look we can define a style and then apply it on various elements. Using styles promotes code reuse, makes our code shorter and assists with the code maintenance in the long run. Defining a style is about defining a collection of property values we can then apply to any element we select. Using styles is very similar to using CSS. In both cases we reuse a style definition.

The style is a resource. We define it as any other resource. Each style includes a collection of Setter elements .Each Setter element sets a specific property. The property must be a dependency one.

Unlike WPF we cannot apply the same style on different types of elements and we cannot use triggers in order to change the style of a given control when a specific property changes its value.

The following code sample includes the definition of a simple style that targets buttons.

<UserControl x:Class="SilverlightApplication30.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <Style x:Key="CuteButton" TargetType="Button">
            <Setter Property="FontFamily" Value="Arial" />
            <Setter Property="FontSize" Value="18" />
            <Setter Property="Foreground" Value="Blue" />
            <Setter Property="Padding" Value="10" />
        </Style>
    </UserControl.Resources>
    <Canvas x:Name="LayoutRoot" Background="White">
        <Button Name="MyBt" Content="Click Here" Style="{StaticResource CuteButton}" />        
    </Canvas>
</UserControl>

The following video clip overviews this code sample and explains it.

Share:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences