This article is currently in the process of being translated into Croatian (~29% done).
Introduction to WPF styles
Ukoliko dolazite iz svijeta razvoja web aplikacija i koristite HTML i CSS, brzo ćete uvidjeti da XAML jako nalikuje HTML-u: koriste se tagovi, definirate strukturni raspored vaše aplikacije. Čak možete napraviti da vaši elementi imaju određeni izgled koristeći svojstva kao što su Foreground, FontSize i tako dalje, kao što možete lokalno stilizirati vaše HTML tagove.
Ali što se događa kada želite koristiti istu veličinu i boju fonta na tri različite TextBlock kontrole? Možete kopirati željena svojstva u svaku od kontrola, ali što se događa kada tri kontrole prerastu u 50 kontrola raspoređenih na više prozora? I što se događa kada zaključite da bi veličina fonta trebala biti 14 umjesto 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.
Summary
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.