Introduction
This article introduces and illustrates the use of Triggers in WPF. This article covers the following topics:
-
What's Triggers in WPF?
-
Why use Triggers?
-
How many types of of triggers are in WPF?
-
Examples of all the Triggers in WPF
What is Trigger
A Trigger is typically used in a Style or ControlTemplate. It triggers on properties of whatever is being templated, and sets other properties of the control (or of specific template elements). For example, you would use a Trigger on IsMouseOver to respond to the mouse being over the control, and the setters might update a brush to show a "hot" effect.
Why do use Trigger?
Triggers are used in styles to perform actions on a change of any property value or event fires. Triggers create visual effects on controls. By using Triggers we can change the appearance of Framework Elements.
How many types of triggers are in WPF?
There are five types of triggers supported by WPF; they are:
-
Property Trigger
-
Data Trigger
-
MultiTrigger
-
MultiDataTrigger
-
Event Trigger
Property Trigger
The simplest form of a trigger is a property trigger, that watches for a dependency property to have a certain value. For example, if we wanted to light up a button in yellow as the user moves the mouse over it, we can do that by watching for the IsMouseOver property to have a value of "True".
Data Trigger
DataTriggers are Triggers that watch a bound value instead of a Dependency Property. They allow you to watch a bound expression, and will react when that binding evaluates equal to your value.
For example, you could set a DataTrigger on "{Binding Value}" or "{Binding ElementName=MyTextBox, Path=IsChecked}". You can even use Converters with DataTriggers, such as:
<DataTrigger
Binding="{Binding SomeInt, Converter={StaticResource IsGreaterThanZero}}"
Value="True">
MultiTrigger
A MultiTrigger is used to set an action on multiple property changes. It will execute when all conditions are satisfied.
For example, suppose we want to change the background color of a TextBox on mouse move, focus and lost focus, for that you can use a MultiTrigger.
<Window x:Class
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MultiTRiggerDEmo" Height="300" Width="300" Loaded="Window_Loaded">
<Window.Resources>
<Style x:Key="MultTrigg" TargetType="{x:Type TextBox}" ="">
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsFocused" Value="True">
</Condition>
Pradeep YadavPosted Mar 8, 2018, 11:53 AM
How to execute trigger if i have condition for value is greater than or less than some value, i.e. if value is greater than 10 then bgcolor red else green
Meer DeenPosted Feb 12, 2016, 12:50 AM
is it possible to make interactivity trigger common?