Skip to main content

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

The objective of this article series is to give a quick overview of Behaviors, Triggers and Actions in Silverlight and WPF.  Together, they enable a great deal of design time interactivity for your UI. They also make possible re-use and re-distribution of interaction logic. This is the second article in the series, and I’ll explain about Triggers and Actions. Also, we’ll explore how to create custom triggers.

Note: You need Expression Blend 4.0

The completed source code for this exercise is available


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.


3.  Modifying ChangePropertyAction image

Now let us squeeze our ellipse a bit by changing the Width property of our Ellipse - when the MouseLeftButtonDown happens. For this, go to the properties window, and


1. Change ‘PropertyName’ parameter of our ChangePropertyAction to ‘Width’.

2. Set the the value to 200 so that Width will increase to 200 when the Action is invoked

3. In the Animation Properties of ChangePropertyAction, set the duration to 4 seconds, and change the Ease property to Elastic Out.

We are done. Run the application, by pressing F5 and move click over the Ellipse. And you’ll see a bit of fun.

Play around with this a bit, to understand how the Triggers and Actions work together. And once you are back, scroll down to read further – about creating our very own Triggers and Actions


Creating a Custom Trigger

Time to go under the skin.  Then, we’ll replace the ‘EventTrigger’ we used in our above example with the custom trigger we are creating, to stretch the ball!!.

First, let us create a minimal custom trigger – named KeyDownTrigger, that’ll be fired each time when a key is pressed. Let us continue from where we left our above project.

Step 1 – Create a Trigger: In Blend, right click your project in the Projects pane, and click ‘Add New Item’, to bring up the New Item dialog box. Select ‘Trigger’ from there, give the name ‘KeyDownTrigger’ and click OK.


Step 2 – Add some meat. Have a look at the New trigger class that got added to your project. You’ll find that our Trigger class is inherited from TriggerBase<T> in System.Windows.Interactivity. Also, have a look at the override methods, OnAttached and OnDetaching (and the comments below them). Let us add some meat to the code you already see there. Modify the code to this.

Tip: If you have Visual Studio 2010 Beta installed, you can right click on a file in Blend 4.0 project explorer, and click ‘Edit in Visual Studio’ at any point of time, if you prefer writing code in VS rather than in Blend.

public class KeyDownTrigger : TriggerBase<FrameworkElement>
		protected override void OnAttached()
	       // Insert code that you want to run when the Trigger is attached to an object.
             this.AssociatedObject.Loaded += (sender, args) =>
                Application.Current.RootVisual.KeyDown +=
                    new KeyEventHandler(Visual_KeyDown);

		protected override void OnDetaching()
			// Insert code that you would want run when the Trigger
			//is removed from an object.
            Application.Current.RootVisual.KeyDown -= 
				new KeyEventHandler(Visual_KeyDown);

        //A property for the trigger so that users can specify keys
        //as comma separated values
        public string Keys { get; set; }

        //Invoke the actions in this trigger, if a key is in the list
        void Visual_KeyDown(object sender, KeyEventArgs args)
            var key = Enum.GetName(typeof(Key), args.Key);

            if (Keys.Split(',').Contains(key))

The code is self explanatory, but here is basically what we are doing there. When the Associated object is loaded, we hook up to the KeyDown event of the Root visual element. And when KeyDown is fired, we Invoke the Actions inside this trigger, if the key is entered by the user.

Step 3 – Associate the KeyDownTrigger to our Ball.

In Blend, click Project->Build Project menu. Now, go back to our MainPage.xaml where you have your ball. As we did earlier, Select the ChangePropertyAction in the Xaml Editor or in the Object and Timelines window, to bring up the Properties Window - as we did earlier. In the Properties window, Click the ‘New’ button against the TriggerType, in the Trigger Pane (see the image). In the resultant dialog box, select the ‘KeyDownTrigger’ we recently added, and click OK.



Now, you’ll see that the ‘EventTrigger’ we had there earlier, got replaced with the ‘KeyDownTrigger’. Note that the ‘Keys’ property we added to our Trigger class is visible in the Blend UI - so that some one who may use our trigger can enter the values there to specify what all keys should invoke the actions inside the trigger. Just enter few key names with out spaces (let us say A,B,C) to the Keys field.



Step 4 – Salvation

Cool, we are done. Press F5 and run your project. Click on the surface to bring focus, and press A,B or C to see the ball getting stretched. Woot!! We just created and implemented a minimal trigger.

Shout it

Popular posts from this blog

MVVM - Binding Multiple Radio Buttons To a single Enum Property in WPF

I had a property in my View Model, of an Enum type, and wanted to bind multiple radio buttons to this.

Firstly, I wrote a simple Enum to Bool converter, like this.

public class EnumToBoolConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (parameter.Equals(value)) return true; else return false; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return parameter; } #endregion }

And my enumeration is like

public enum CompanyTypes { Type1Comp, Type2Comp, Type3Comp } Now, in my XAML, I provided the enumeration as the ConverterParameter, of the Converter we wrote earlier, like

Creating a quick Todo listing app on Windows using IIS7, Node.js and Mongodb

As I mentioned in my last post, more and more organizations are leaning towards Web Oriented Architecture (WOA) which are highly scalable. If you were exploring cool, scalable options to build highly performing web applications, you know what Node.js is for.After following the recent post from Scott Hanselman, I was up and running quickly with Node.js. In this post, I’ll explain step by step how I’ve setup Node.js and Mongodb to create a simple Todo listing application.Setting up Node.jsThis is what I’ve done.1 – Goto, scroll down and download node.exe for Windows, and place it in your c:\node folder2 – Goto IIS Node project in Git at, download the correct ‘retail’ link of IIS Node zip file (I downloaded the already built retail package, otherwise you can download and build from the source).3 – Extract the zip file some where, and run the install.bat or install_iisexpress.bat depending on your IIS Version. If you don’t have IIS in…

Top 7 Coding Standards & Guideline Documents For C#/.NET Developers

Some time back, I collated a list of 7 Must Read, Free EBooks for .NET Developers, and a lot of people found it useful. So, I thought about putting together a list of Coding Standard guidelines/checklists for .NET /C# developers as well.As you may already know, it is easy to come up with a document - the key is in implementing these standards in your organization, through methods like internal trainings, Peer Reviews, Check in policies, Automated code review tools etc. You can have a look at FxCop and/or StyleCop for automating the review process to some extent, and can customize the rules based on your requirements.Anyway, here is a list of some good Coding Standard Documents. They are useful not just from a review perspective - going through these documents can definitely help you and me to iron out few hidden glitches we might have in the programming portion of our brain. So, here we go, the listing is not in any specific order.1 – IDesign C# Coding StandardsIDesign C# coding stand…