Infragistics Developer Evangelist | Microsoft MVP

Menu

Behavior in SILVERLIGHT 3.0

This article will give a basic introduction of BEHAVIOR feature in SILVERLIGHT3.0. I will also walkthrough to create a custom behavior.

What is Behavior in SILVERLIGHT 3?

According to definition given in the product introduction of SILVERLIGHT3

A Behavior is in essence a reusable piece of interactivity that can be applied directly to user interface elements in Expression Blend. The whole product introduction on behavior can be read here.

I summarized few of the points as below about SILVERLIGHT behavior

Behavior is new feature introduced in SILVERLIGHT 3.0.

Behavior is a reusable piece of code, which can be attached to any object declaratively.

Behavior is the way to allow designer to add functionality to XAML elements without codes.

Behavior allows attaching functionality to an object without writing any code.

Behavior encapsulates the functionality and can be attached to any element.

Behavior can be attach to an element or object through XAML. There is no need to write C# code.

A single behavior can be attached to any number of objects.

Behavior is reusable piece of code can be attached to any object.

Behavior comes with System.Windows.Interactivity.dll

Creating a Custom BehaviorStep 1Create a SILVERLIGHT Application. Two projects will get created SilverLightApplication1 and SilverLightApplication1.Web. If you are not, changing the default name. Add reference of System.Windows.Interactivity.dll in SilverLightApplication1 project.

Step 2

Right click on SILVERLIGHT project and add a class. Give any name, for my purpose; I am giving name ImageBehavior.

Add the namespace using System.Windows.Interactivity;

Inherit class from Behavior<T>

Make T as DependencyObject

Override the methods OnAttached and OnDetaching

On MouseEnterevent and MouseLeave event write the simple logic to rotate the object to which Behavior will be attached.

First namespace is for the System.Windows.Interactivity dll and second one is namespace of the custom behavior class.

Step 2

Since; I am going to attach the custom behavior we created with Image control. So for the source of Image control add an image to SILVERLIGHT project by Add an existing item. I have added an image and gave the name a.jpg.