Tuesday, March 08, 2011

Behaviors, Triggers and Actions in Silverlight And WPF Made Simple – Part 2 – Triggers

Triggers and Actions – Scratching the Surface

A Trigger can invoke a set of Actions, when it is fired. For example, you can nest few actions (like PropertyChangeAction to change a property of an element) in an EventTrigger, so that those actions will get executed when a specific Event occurs. You can attach more than one trigger to an element.
If you have some WPF background, you may quickly remember the DataTriggers, MultiDataTriggers etc.

There are various Triggers and Actions that comes ‘out of the box’, residing in System.Windows.Interactivity and Microsoft.Expression.Interactions

Triggers – EventTrigger, TimerTrigger, StoryBoardCompletedTrigger, KeyTrigger etc.
Actions - ChangePropertyAction, ControlStoryBoardAction, PlaySoundAction etc.

Let us start playing with some of the existing triggers and actions.

1.  Set The Stage - Create a new Silverlight Application Project in Blend (as explained in my previous post). You’ll see the design surface of MainPage.xaml by default. This time, select the Ellipse tool from Blend toolbar, to draw a ball to the design surface. Give some nice color as well :)
Also, at this point, click View->Active Document View->Split View – So that you can view the Xaml along with the designer.

2. Attach a Trigger and Action to an object – Go to the Assets pane in Blend, and click the Behaviors link. Drag the ChangePropertyAction to the ellipse you added, and have a look at the XAML. You’ll find that Blend automatically added an EventTrigger for you with MouseLeftButtonDown as the default event, and sandwiched your ChangePropertyAction inside the same.


Select the ChangePropertyAction in the Xaml Editor or in the Object and Timelines window. Have a look at the properties Window in blend, to see the properties of your Trigger and Action (See the image below). By default the trigger will be fired for the MouseLeftButtonDown event of our ball. Also, you may note that presently we havn’t specified any parameters for the ChangePropertyAction.