Let’s say you have WPF UI which has lot of buttons and you want to set the back ground to “Aqua” color.
So the quick way of doing is to set background of all the buttons to “Aqua” color as shown in the below XAML code. But now let’s say some days down the line customer wants to change the background color to “Red” . So you need to modify the background property for all buttons.
Won’t it be great if we can define the background color as a style from some common place and when we want to change the back ground color we just change from that central common place. That’s what WPF style helps us to achieve.
WPF style helps to define look and feel ( color , fonts , alignments etc) from a central location so that we can have ease of maintenance.
To define a style we need to use the “Style” tag of XAML. It needs three things atleast :-
- X:Key :- Name of Key of the style.
- TargetType :- WPF UI object on which you want to apply style. For example in the below code we are applying this style on the button.
- Setter :- This element defines the property for which the value has to be set. For example in our case we are setting the “Background” color property to “Aqua”.
Once the style is defines we can attach the style resource to the style property of button element as shown in the below code.
One more famous C# WPF interview question is “Why should we use WPF over Winforms ?”. Below video explains the same in more detail. This video is created by www.questpond.com they deliver training in Advanced WPF.