Sunday, 10 February 2013

Triggers in WPF

What are triggers?


Triggers have a collection of Setters which  performs its work based on one or more conditions.

Example: Setting up style of elements.

Three types of Triggers:


Property triggers—Get invoked when the value of a dependency property changes
Data triggers—Get invoked when the value of a plain .NET property changes
Event triggers—Get invoked when a routed event is raised

Property Trigger:


In following trigger, data binding is used to provide an appropriate message inside the
ToolTip when validation error occurs.



<Style x:Key=”MyTextBoxStyle” TargetType=”{x:Type TextBox}”>
<Style.Triggers>
<Trigger Property=”Validation.HasError” Value=”True”>
<Setter Property=”Background” Value=”Red”/>
<Setter Property=”ToolTip”
Value=”{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}”/>
</Trigger>
</Style.Triggers>
</Style>
<TextBox Style=”{StaticResource MyTextBoxStyle}”>

Data Trigger