WPF Triggers

Triggers come in three main varieties in XAML. They are part of a style that allows for dynamic behaviour in the appearance of a control.

Any Trigger has two main parts: the item to watch, a value at which the behaviour is triggered and the properties to set values on when the trigger fires.

Property Triggers

Fire when a targeted property changes on the control.

<Style.Triggers>
  <Trigger Property="Content" Value="{x:Null}">
    <Setter Property="ToolTip" Value="Control is empty" />
  </Trigger>
</Style.Triggers>

In this example the tooltip is set if the control has no content.

Property triggers can be dependent on more than one property:

<Style.Triggers>
  <MultiTrigger>
    <MultiTrigger.Conditions>
      <Condition Property="IsFocused" Value="True"/>
      <Condition Property="Content"   Value="{x:Null}" />
    </MultiTrigger.Conditions>
    <Setter Property="Background" Value="Green"/>
  </MultiTrigger>
</Style.Triggers>

Data Triggers

Display behaviour can also be triggered by the value of bound data:

<Style.Triggers>
  <DataTrigger Binding="{Binding Path=CurrentPlayer}" Value="0">
    <Setter Property="Background" Value="Red"/>
  </DataTrigger>
</Style.Triggers>

Event Triggers

Event triggers fire on a UI event.

<Style.Triggers>	
  <EventTrigger RoutedEvent="Click">
    <BeginStoryboard>
      <Storyboard>
        <DoubleAnimation Storyboard.TargetProperty="Opacity" 
                            From="0" 
                            To="1" 
                            Duration="0:0:2" />
      </Storyboard>
    </BeginStoryboard>
  </EventTrigger>
</Style.Triggers>

In this case an animation is triggered instead of a property change.

Leave a Reply