Attaching Silverlight 3 Behaviors in C#

For the most part we'll be adding or manipulating Silverlight / WPF Behaviors from Blend, but occasionally we'll need to manage these from code. Overall it's a pretty simple process. The main class we need to deal with is Microsoft.Expression.Interactivity.Interaction, from here we can retrieve the Behaviors and Triggers collections for a DependencyObject.

To attach a standard Behavior we use the following code.

var scrollBehavior = new MouseWheelScrollBehavior();

 

var behaviours = Interaction.GetBehaviors(Viewer);   

 

behaviours.Add(scrollBehavior);

 

To remove an attached behavior we use the following.

behaviours.Remove(scrollBehavior);

 

Managing triggers and actions are a two step process. In Blend elements have triggers and triggers have actions. You can have multiple actions per trigger, and multiple triggers per element. First we create our trigger and our action, we then add our action to the trigger's actions collection and finally the trigger to the element's triggers collection.

var trigger = new RandonTimerTrigger();

var action = new MessageBoxAction();

 

trigger.Actions.Add(action);

 

var triggers = Interaction.GetTriggers(Viewer);

 

triggers.Add(trigger);

 

Removing an action from a trigger or a trigger from an element is similar process to behaviors.

triggers.Remove(trigger);

 

kick it on DotNetKicks.com

Shout It Kick It submit to reddit

4 Comments

  1. DotNetKicks.com
    DotNetKicks.com
    Wednesday, June 17, 2009
    Trackback from DotNetKicks.com Attaching Silverlight 3 Behaviors in C#
  2. Sanjeev Agarwal
    Sanjeev Agarwal
    Thursday, June 18, 2009
    Trackback from Sanjeev Agarwal Daily tech links for .net and related technologies - June 16-18, 2009
  3. WebDevVote.com
    WebDevVote.com
    Thursday, June 18, 2009
    Trackback from WebDevVote.com Attaching Silverlight 3 Behaviors in C#
  4. Edward Moemeka
    Edward Moemeka
    Tuesday, July 14, 2009
    You neglected to mention the need to have System.Windows.Interactivity and Microsoft.Expression.Interactions assemblies.

Comments are closed