XAML Review
www.shaxam.com

Triggers in XAML

Posted in Software

Triggers allow you to change attributes of an element when a specific action occurs. For example, you can change the font color of text when the mouse hovers over it, or change the width of a button once it has been clicked. Triggers can act on single instances of an element, or affect an entire class of elements.

Triggers are conditional. They are essentially a way to implement standard if…then logic without writing external code. In other words, a trigger evaluates an attribute and if the current value of that attribute matches the value specified by the trigger, then the style is applied. If the cursor moves over a Button, then change the background to green.

The code adds a TRigger that will fire when the property Button.IsMouseOver is TRue. Two Setter elements define the attributes we wish to change when the condition of the trigger is met. In this case, it changes the foreground of the Button to green and the background to red.

Using a Trigger to modify the appearance of Button elements
xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005">

TargetType="{x:Type Button}">

Property="Button.IsMouseOver"
Value="true">
Property = "Foreground"
Value="Green"/>
Property = "Background"
Value="Red"/>





Content="My Button" />

Above code will modify the appearance of all Button elements declared in the page. To target only a specific Button, you must reference the style from the Button element. To do this, you must add a key name to the trigger and declare it as the Style attribute of the Button. The resulting code is shown below:

Using a Trigger to modify the appearance of a single Button
xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005">

x:Key="ButtonTriggers"
TargetType="{x:Type Button}">

Property="Button.IsMouseOver"
Value="true">
Property = "Control.Foreground"
Value="Green"/>
Property = "Control.Background"
Value="Red"/>





Style="{StaticResource ButtonTriggers}"
Content="My Button" />

Above code shows how to declare TRiggers local to an element by defining the TRiggers within the local element’s Resources attribute. As mentioned previously, local resources override global resources, so these resources will be applied to the element in which they are defined, but not to any others.

This flexibility allows you to define conditional styling in a variety of ways, either by targeting a specific class of elements or individual elements. When used in conjunction with templated styles, triggers provide a powerful mechanism for designing rich, interactive user interfaces.

Thanks for Reading.