WPF Style – Triggers – BasedOn – Setters – Resources

WPF Style class comprise of triggers, based on style, setters and resources in the scope of style.  Any element that derives from FrameworkElement or FrameworkContentElement has style property whcih you can set either through code or through markup. Style ican be declared as a resource inside the Resources section. Styles are resources and they obey rules that apply to all resources, so where you declare a style affects where it can be applied. If, for instance, you declare the style in the application resource then style can be used anywhere in your application. If you are creating a navigation application and declare the style in one of the application’s XAML files, the style can be used only in that XAML file.



The style object contains a collection of
1. One or more Setter objects where each Setter consists of a Property and a Value. The property is the name of the property of the element the style is to apply to. After the style is declared as a resource, it can then be referenced just like any other resource. If there is more than one setter in the setter collection with the same Property property value, the setter that is declared last is used. Similarly, if you set a value for the same property in a style and on an element directly, the value set on the element directly takes precedence.
2. One or more triggers which can be simple triggers,data trigger,event triggers or multi triggers.

Style can inherit from other style which can set to Based On property of style. Which means you can inherit all features of parent style and change whatever you want.

Resources can be declared in scope of style and hence only illegible to be used in the same or derived style.WPF supports style and templates to separate look and logic of wpf elements. Styles can be applied to all elements of a given type by using the TargetType property. Adding the target type to the style means that you no longer have to fully qualify the property you are setting with the ClassName.PropertyName syntax.

The following example defines a style that will be applied to every Label element.

<Style x:Key="Style1" TargetType="{x:Type Label}">
  <Setter Property="Control.Background" Value="Red"/>

<Label Content="Yellow Background" Style="{StaticResource Style1}" />

<Style x:Key="Style2" BasedOn="{StaticResource Style1}">
  <Setter Property="Control.Foreground" Value="Green"/>

Here style two has inherited Style1. Hence element to which style 2 will be applied will have Background Red and foreground Green
<Style x:Key=”Style1″ TargetType=”{x:Type Label}”>
<Trigger Property=”IsMouseOver” Value=”true”>
<Setter Property = “Control.Foreground” Value=”Blue”/>
You can also add triggers to style. In example above if you hover cursor over label control tha foreground will change to Blue.

Leave a Reply

Your email address will not be published. Required fields are marked *