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
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
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
Title="SimpleStyleSample" Height="200" Width="250">
<Setter Property="Foreground" Value="Gray" />
<Setter Property="FontSize" Value="24" />
<TextBlock Foreground="Blue">Header 3</TextBlock>
For the resources of my StackPanel, I define a Style.
I use the TargetType property to tell WPF that this style should be
ALL TextBlock controls within the scope (the StackPanel), and then I
add two Setter elements to the style. The Setter elements are used to
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
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 section.