WPF Basics - Triggers

Triggers are implemented as part of styles, and indicate a trigger condition and a new set of setters to apply when the trigger condition is met. Mouseover effects are a very common application of triggers. Triggers can fully be expressed using XAML, eliminating the need to write code for many simple effects.

There are three types of triggers in WPF:

  1. Property Triggers - run when the value of a dependency property changes
  2. Data Triggers - run when the value of any .NET property changes, using data binding
  3. Event Triggers - run when a routed event occurs
Triggers are implement as part of a style using the <Style.Triggers> property element, and a series of <Trigger>,<DataTrigger>, or <EventTrigger> elements.

Property Triggers

Property triggers are used to monitor a DependencyProperty's value. The following example applies a glow effect to a button when the mouse pointer is over the button (IsMouseOver=true). The WPF framework automatically handles resetting the style back when the mouse pointer is moved off the button.
<Canvas> <Canvas.Resources> <Style TargetType="{x:Type Button}"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="BitmapEffect"> <Setter.Value> <OuterGlowBitmapEffect GlowColor="Gold" GlowSize="10" /> </Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> </Canvas.Resources> <Button Canvas.Left="19" Canvas.Top="19" Width="75" Height="22">Button 1</Button> </Canvas>

Copyright 2008 - www.WPFDude.com