Triggers

So far, we've seen styles as a collection of Setter elements. When a style is applied, the settings described in the Setter elements are applied unconditionally (unless overridden by per-instance settings). On the other hand, property triggers are a way to wrap one or more Setter elements in a condition. With a property trigger, if the condition is true, the corresponding Setter elements are executed to set one or more element properties. When the condition becomes false, the property values revert to their pre-trigger values.

Property triggers are not the only kinds of triggers that WPF supports, however. With an event trigger, the trigger is activated when an event is fired, which fires off another event to start or stop an animation.

Property Triggers

The simplest form of a trigger is a property trigger, which watches for a dependency property on the element to have a certain value. For example, we might want to set the tool tip over a button if neither player has yet chosen it for a move. We can do so by watching for the Content property to have a value of null,[54] as shown in Example 8-23.

Example 8-23. A simple property trigger

<Style TargetType="{x:Type Button}">
  ...
  <Style.Triggers>
    <Trigger Property="Content" Value="{x:Null}" >
      <Setter Property="ToolTip" Value="click to move here" />
    </Trigger>
  </Style.Triggers>
</Style>

Triggers are grouped together under the Style.Triggers element. In this case, we've added a Trigger element to the button style. When the

Get Programming WPF, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.