Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Monday, July 23, 2012

Triggers in Styles

Triggers in Styles

Triggers define a list of setters that are executed if the specified condition is fulfilled. WPF knows three diferent types of triggers
  • Property Triggers get active, when a property gets a specified value.
  • Event Triggers get active, when a specified event is fired.
  • Data Triggers get active, when a binding expression reaches a specified value.

Property Triggers

A property trigger activates a list of setters when a property gets a specified value. If the value changes the trigger undoes the setters.
 
<Style x:Key="styleWithTrigger" TargetType="Rectangle">
    <Setter Property="Fill" Value="LightGreen" />
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Fill" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>
 
<Rectangle Style="{StaticResource styleWithTrigger}"></Rectangle>
 
 

Event Triggers

Data Triggers

Multi Triggers

Trick to use triggers everywhere

Triggers are only available in styles and templates. Even if every control has a property Triggers, it only works with EventTriggers. If you want to use normal triggers outside a style or a template, you can use a little trick. Just wrap your code with the following snippet:
 
<Control>
    <Control.Template>
        <ControlTemplate>
            <!-- Triggers are available here -->
        </ControlTemplate>
    </Control.Template>
</Control>

No comments:

Post a Comment