Create and Apply Custom Styles in a Windows Store App

In this article, you will learn how to create and apply custom styles in a Windows Store app.

In my previous article, I talked about How to Apply System Resources to Controls. In this article, I will show you how to create your own custom style and apply it to controls in a Windows Store app.

Background

Create a blank Windows Store App and place three controls on your MainPage, a Button, a TextBox and a TextBlock. Give your controls names. I named them TextBlock and HelloTextBlock.

Create Custom Style

Select a control (HelloTextBlock in my case).

Open the Properties window (hit F4).

Now expand the Miscellaneous group and find the Style property.

Click the property marker next to the Style property to open the menu.

Select Convert to New Resource option. You will see the Create Style Resource dialog.

See Figure 1.
 
 
Figure 1 

In this dialog, you provide the style resource name and if you want to define it as the application level or the document level. The application-level resources are defined in the App.xaml and the document level resources are defined in the page XAML.

Select OK on the preceding dialog.

This action defines a Style at the Page.Resources with default values.

<Page.Resources>

        <Style x:Key="GreenTextBlockStyle" TargetType="TextBlock">

Delete all the default values then set the following values for the foreground, font and trimming.

 <Page.Resources>
        <Style x:Key="GreenTextBlockStyle" TargetType="TextBlock">

            <Setter Property="Foreground" Value="Green"/>

            <Setter Property="FontSize" Value="42"/>

            <Setter Property="FontFamily" Value="Verdana"/>

            <Setter Property="TextTrimming" Value="CharacterEllipsis"/>

            <Setter Property="TextWrapping" Value="Wrap"/> 

        </Style>

    </Page.Resources>

Apply Custom Style to a Control

We can apply a style to a control by setting its Style property in XAML or using the designer. Since we created our style using the designer, the Style property is already set for the TextBlock GreenTextBlockStyle as a StaticResource.

<TextBlock x:Name="HelloTextBlock" HorizontalAlignment="Left" Height="208" Margin="60,313,0,0"

                   TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"

                   Width="952" FontSize="48"

                   Style="{StaticResource GreenTextBlockStyle}" />

Now if you build and run the app, you will see the text of the TextBlock is changed to Green. See Figure 2.

Figure 2.
 

Summary

Developers often need to create their own styles for UI. Using this method, you can create your own styles for the entire screen and controls.