My Master's Thesis Problems and solutions encountered…

11Apr/100

Defining Styles at Application Level

When you have many subpages containing buttons, textblocks, stackpanels, etc., it is convenient to define the styles at application level. This way, all objects have the same design, and if you need to change the look and feel of your template, you only need to change it one place, like you would do with CSS when working with HTML.

In your Silverlight application, open your App.xaml , which should look something like this:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 x:Class="QM_v1.App">

    <Application.Resources>


    </Application.Resources>

</Application>


So, in this example we want to define a shared style for all textblocks, so they all have the same color, font, margin, and so forth. Inside your Application Ressource you will define a new Style, width the Setter Property and Setter Value. Like this:



 <Application.Resources>

        <Style x:Key="Normal_text" TargetType="TextBlock">
            <Setter Property="Fontsize" Value="12"/>
            <Setter Property="FontFamily" Value="Verdana"/>
            <Setter Property="Foreground" Value="#FF696969"/>
            <Setter Property="Margin" Value="5"/>
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>

    </Application.Resources>

The Key is the unique name of the Style, while with the TargetType you define which object you want to work with. The Property and Value sets the variables. Note that Visual Studio does not auto-compete inside the Setter, so you need to be careful when writing the names of the variables.

Having defined the style, you just need to write: Style = "{Static Resource Style_name}" when defining your Textblock:


              <TextBlock Text="This text has the style that was defined in the App.xaml.  "
                Style="{StaticResource Normal_text}"
               />


Of course, this method can be used with Grids, StackPanels, buttons... everything. Very useful!

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


− 5 = three

No trackbacks yet.