This article is currently in the process of being translated into Korean (~13% done).


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"
        Title="SimpleStyleSample" Height="200" Width="250">
    <StackPanel Margin="10">
            <Style TargetType="TextBlock">
                <Setter Property="Foreground" Value="Gray" />
                <Setter Property="FontSize" Value="24" />
        <TextBlock>Header 1</TextBlock>
        <TextBlock>Header 2</TextBlock>
        <TextBlock Foreground="Blue">Header 3</TextBlock>

StackPanel의 resources에 대해 Style을 정의합니다 . WPF에 TargetType 속성을 사용하여 범위(StackPanel) 내의 모든 TextBlock 컨트롤에 이 스타일이 적용되어야 한다고 알리고, 두 Setter 요소를 추가합니다. Setter 요소는 대상 컨트롤의 특정 속성(이 경우 ForegroundFontSize)을 설정하는 데 사용됩니다. Property는 WPF에 대상으로 지정하려는 속성을 알려주고 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.


WPF styles make it very easy to create a specific look and then use it for several controls, and while this first example was very local, I will show you how to create global styles in the next chapters.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!