Tuesday, August 13, 2013

WPF Behavior and Trigger

Behaviors are a new concept, introduced with Expression Blend in Version 3, to encapsulate pieces of functionality into a reusable component. These components than can be attached to controls to give them an additional behavior.
The ideas behind behaviors are to give the interaction designer more flexibility to design complex user interactions without writing any code.
Example of a behaviors are drag&drop, input validation, pan and zoom, re-position of elements, etc... The list of possible behaviors is very long.
Imaging an application that has a list of customers and the user can add some of them to subscriber lists. This interaction can be designed by providing an "Add" button next to each subscriber list. But if the interaction designer wants to add drag&drop functionality, he needs to discuss it with the developer and wait until the implementation is done. With behaviors he just drags a drag and drop behavior on each list and we are done.

To add behaviors to an element you need some kind of an extension point. This is an attached property calledInteraction.Behaviors.
This attached property holds the list of behaviors for that element and pass a reference to the element into the behavior. The behavior than can register itself to events and property changes and so extend the functionality of the element.


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>

No comments:

Post a Comment