Using XAML StyleSheets (Universal Windows Apps)

You can use StyleSheets with XAML and get the same general advantages of CSS StyleSheets, namely a more consistent layout, easier to maintain and reduction of clutter in your main layout.

You can use StyleSheets with XAML and get the same general advantages of CSS StyleSheets, namely a more consistent layout, easier to maintain and reduction of clutter in your main layout.

For example, here we have a Stack Panel with a couple of Text Blocks:

        <StackPanel x:Name="pnlbody" 
           HorizontalAlignment="Center" 
           Width="350" 
           Padding="0" 
           Margin="0,70,0,0"  
           VerticalAlignment="Top" >
            <TextBlock />
            <TextBlock />
        </StackPanel>
        

You can reduce this code to:

        <StackPanel x:Name="pnlbody" Style="{ThemeResource BodyStyle}">
            <TextBlock />
            <TextBlock />
        </StackPanel>
        

and then define a StyleSheet like:

    <Style x:Key="BodyStyle" TargetType="StackPanel">
        <Setter Property="HorizontalAlignment" Value="Center" />
        <Setter Property="Width" Value="350" />
        <Setter Property="Padding" Value="0"  />
        <Setter Property="Margin" Value="0,70,0,0"  />
        <Setter Property="VerticalAlignment" Value="Top" />
    </Style>
        

You can see how this is built. A particular Style is associated with the TargetType (in this case a StackPanel, but can be a TextBlock, Image or any XAML control) and then whatever properties you originally defined must be placed in a Setter block of Property and Value.

In a Visual Studio project, StyleSheets can usually be found in the {project_root}/Styles/Styles.xaml. You can start by simply adding definitions into that. If you use a separate file then don’t forget to add a definition in the app.xaml file.