WPF: Static resources and styling

Nau mai!
Today it’s going to be about styling in WPF. So far all UIs I designed in WPF had all controls styled in their definitions. This worked sufficiently well as I have not yet built any complex application. But, it is obvious that is not to any degree an effective way to achieve styling of UI elements. My understanding of how to built bigger and more complex UI and to keep them consistent appearance-wise would be to use something like CSS in web design. And in fact WPF allows us to use similar method. Create a definition of element’s look and then assign it to an actual control in the interface.
Styles can be defined for each container. For instance, you can define style for elements in a panel, but you can also define style for whole window or even application.

Internal styles
Let’s start with styles defined inside a file where the styles are going to be used. The code below presents how to define styles available for all window elements.

In the example above we create static resources that are available for all elements in current window. Then, inside resource we create a style definition where we set style key and target type (this is optional, however to have access to control-specific properties it is recommended to do so). Now, to set specific property we use property setters where we declare a property name and assign value to it. Once, the style is defined it can be assigned to a control. The XAML code above would generate that window:

To define styles available for elements only in one container (e.g. in a panel) we need almost exactly the same code. The only change would be that the resources are set for a stack panel not for window (StackPanel.Resources instead of Window.Resources).

External resources
To reuse the same styling in multiple windows we need to create a resource dictionary. It is nothing else than a XAML file. Simply right click on your project in Solution Explorer and go Add and then Resource Dictionary.

In that file you declare styles as you like for various controls, then you put path to this file in Resources section of any container you want to style:

It is also possible to put it in application’s resources having the styles available in whole app.

In the code above there are MergedDictionaries specified. This allows to use multiple resource dictionaries in one container. If a key exists in more than one source dictionaries the last one specified will be used.

Triggers
Triggers can be used to specify certain conditions that must occur to enable the style (the most common example: a button is hovered).

The code above will make a button to change its properties if IsMouseOver property is set to true.
So, that’s it for today. I know that styling in WPF is much more vast topic and surely I will come back to it, but this basic introduction is sufficient for me for the time being.
Thanks you, Michal.