WPF – Triggers and Styles – Pro WPF 4.5 in C# book

Some time ago I started reading this book – Pro WPF 4.5 in C#. As far as it was given to me in order to write some reviews on it, today I have decided to write something about chapter 11. What chapter 11 tells us? Pretty much the chapter is named “Styles and Behaviours” and it explains anything you want to know about styles and behaviours in WPF with C# and even beyond that. In this article I would explain something about styles and Event Triggers in WPF 4.5 and I would not write about behaviours.

So, long story short – what is a style? The book says “A collection of property values that can be applied to an element”. Or with other words, we may say – “I want to define a style called “GreenItalicButton” and whenever I apply it to an element “Button” I get a button with italic name and green background.

What is a trigger?  It is better to see it, than to read about it. The book says that triggers are linked to styles through the Style.Trigger collection. Roughly, they are attached to dependency properties and you can create some events by responding to changes in IsFocused, IsMouseOver, IsPRressed properties of the Control Class </end of copy paste from the book>.

Let’s check the example:


We have 3 buttons in a stack panel. Nothing unusual. The interesting part is that we have declared 3 styles in WPF, in order to make our buttons.

Here is the first style:

What does it do? Actually, nothing, but if you implement it to a button it makes it font “Times New Roman”, its font size 17 and its font value – bold. All the buttons are using this style.

Here is the second style:

This style inherits the first style and it changes the foreground and the background of the button. Furthermore, we have two triggers on it – a normal one and event trigger. The normal one changes the background of the button, once the mouse is over. The event trigger increases the font size of the button to 22 for 2 seconds, once the mouse is over.

The third style looks like this:

It inherits the second one, which inherits the first one. It changes the font style to “Italic”. One more style is added – if you press the button, its font color is changed to red.

Pretty much that is all. Here is the whole WPF code together:

If you want to download the application and see how it works, you may do so here.

Enjoy it!

Tagged with: , , ,