Jul 16, 2015

Introduction to WPF styles

If you come from the world of developing for the web, using HTML and CSS, you'll quickly realize that XAML is much like HTML: Using tags, you define a structural layout of your application. You can even make your elements look a certain way, using inline properties like Foreground, FontSize and so on, just like you can locally style your HTML tags.
But what happens when you want to use the exact same font size and color on three different TextBlock controls? You can copy/paste the desired properties to each of them, but what happens when three controls becomes 50 controls, spread out over several windows? And what happens when you realize that the font size should be 14 instead of 12?
WPF introduces styling, which is to XAML what CSS is to HTML. Using styles, you can group a set of properties and assign them to specific controls or all controls of a specific type, and just like in CSS, a style can inherit from another style.

Basic style example

We'll talk much more about all the details, but for this introduction chapter, I want to show you a very basic example on how to use styling: 


<Window x:Class="WpfTutorialSamples.Styles.SimpleStyleSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SimpleStyleSample" Height="200" Width="250">
    <StackPanel Margin="10">
        <StackPanel.Resources>
            <Style TargetType="TextBlock">
                <Setter Property="Foreground" Value="Gray" />
                <Setter Property="FontSize" Value="24" />
            </Style>
        </StackPanel.Resources>
        <TextBlock>Header 1</TextBlock>
        <TextBlock>Header 2</TextBlock>
        <TextBlock Foreground="Blue">Header 3</TextBlock>
    </StackPanel>
</Window>
 
For the resources of my StackPanel, I define a Style. I use the TargetType property to tell WPF that this style should be applied towards ALL TextBlock controls within the scope (the StackPanel), and then I add two Setter elements to the style. The Setter elements are used to set specific properties for the target controls, in this case Foreground and FontSize properties. The Property property tells WPF which property we want to target, and the Value property defines the desired value.
Notice that the last TextBlock is blue instead of gray. I did that to show you that while a control might get styling from a designated style, you are completely free to override this locally on the control - values defined directly on the control will always take precedence over style values.
 

No comments:

Post a Comment