WPF Triggers

Kailash Chandra Behera | Saturday, June 25, 2016


Triggers in WPF is same as like triggers in SQL, This article describes about WPF trigger, different types of triggers are available in WPF.

Getting Started

Triggers are a very important feature of WPF that helps to change the visual effect of a framework element or control. Triggers are typically used in styles or ControlTemplate to change the visual effect of a WPF element when a property or data is changed or an event is fired. For changing the visual effect of a WPF element, triggers reduce the code in code behind.

For example, let's say you have a rectangle control. You want to change the background color of that control when the mouse hovers over the rectangle control and revert back when mouse leaves. For this you need to code in the mouse hover event and mouse leave event of the rectangle control in the backend class for changing the color of rectangle as in the following code.

 private void Rectangle_MouseMove_1(object sender, MouseEventArgs e)   
   this.rctback.Fill = Brushes.Red;   
 private void Rectangle_MouseLeave(object sender, MouseEventArgs e)   
   this.rctback.Fill = Brushes.Green;   

In the preceding code you have filled the background color of the Rectangle control by writing code in two different events, but a trigger helps to overcome this problem by reducing the code. See the following example.

 <Rectangle Name="rctback" HorizontalAlignment="Left" Height="100" Stroke="Black" VerticalAlignment="Top" Width="100" Margin="178,92,0,0" >   
         <Style TargetType="Rectangle">   
           <Setter Property="Fill" Value="Green"></Setter>   
             <Trigger Property="IsMouseOver" Value="True">   
               <Setter Property="Fill" Value="Red" />   

Types of Trigger

Mainly there are four types of trigger in WPF. The triggers are like this

  1. Property Trigger

    This is the default trigger in WPF. This trigger gets fired when property of target element or own control is changed.

  2. Data Trigger This trigger is fires when the data bound with the control is changed and matches the condition.
  3. Event Trigger An Event trigger is fired when an event fired by UI Element.


We have discussed about Trigger of WPF in this article, hope this article may helpful to you.