Kailash's Blogs

WPF Property Trigger

Kailash Chandra Behera | Wednesday, July 06, 2016
Kailash's Blogs


This article demonstrates how to use Property trigger with WPF UI controls and briefs little about Property Trigger. In this article we have covered example of both XAML and Behind code.

Getting Started

A Property Trigger gets executed when property of WPF UI control is changed. For example TextBlockForegroundcolor can be changes with the help of property trigger when IsMouseOverproperty is gets changed.

Triggers are declared with style and the setter property is used with in the trigger to gets change the target Control. The syntax of declaring trigger in XAML is like below.

 <Style TargetType="typ_of_control" x:Key="key_name_of_style">  
           <Trigger Property="Name_Of_Property" Value="value_Of_Property">  
                <Setter Property="PropertyName_Of_Target_Element" Value="Value_To_Be_Change"></Setter>  

The Property Named 'Property' in trigger accepts the name of property of bound element (whose visual is going to change) that means the trigger will check the value of that property. The Value property of the trigger accepts the value, based whom trigger will execute that means trigger will be fired when property value of bound element matches the provided value .

The setters in trigger is collection of setter object, the setter object is actually changing the UI element vitality. The property named 'Property' accepts the value that is going to be changes based on the Value property of setter.

XAML Code Example

Declaration Trigger in XAML
  <Style TargetType="TextBlock" x:Key="tbktrigger">  
         <Trigger Property="IsMouseOver" Value="true">  
           <Setter Property="Foreground" Value="Red"></Setter>  
Use of Trigger
  <TextBlock Style="{StaticResource tbktrigger}" x:Name="textBlock" Text="Property Trigger Example"/>  

Behind Code Example

This example demonstrates how to declare trigger using behind code in C# and use that style into controls. it also gives example how to use style for trigger when you declared in xaml.
  Style style = new Style();  
       style.TargetType = typeof(TextBlock);  
       Trigger trigger = new Trigger();  
       trigger.Property = TextBlock.IsMouseOverProperty;  
       trigger.Value = true;  
       Setter setter = new Setter();  
       setter.Property = TextBlock.ForegroundProperty;  
       setter.Value = Brushes.Red;  
       this.textBlock.Style =style;  
When Style Declared in XAML and Use in Behind Code
  this.textBlock.Style = (Style)Application.Current.Resources["ListViewItemTextBlockStyle"];  

Related Articles

  1. WPF Event Trigger
  2. WPF Data Trigger
  3. UpdateSourceTrigger
  4. WPF Triggers
  5. WPF Converters


IN this article we demonstrate how to declare property trigger and how to use that in both xaml and behind code. Hope this demonstrator will make you helpful.