Silverlight Behaviors and Commands

By Fons Sonnemans, posted on 21-Dec-2009
1073 Views

A few months ago I wrote an blog post about a Silverlight 3.0 LetItSnowBehavior. This Behavior can be used to add a Snow effect to a Canvas. Very usefull if you want to create a christmas card.

This behavior was always showing you falling snow flakes. You couldn't stop and (re)start the gameloop. The best way to implement this is by adding Commands to the behavior. This allows you to select one or more triggers to Start or Stop the gameloop. I have added the Start and Stop properties of the type ICommand to the LetItSnowBehavior class. In the constructor I have initialized these properties with new ActionCommand objects (Microsoft.Expression.Interactions.dll) and delegates to the OnStop() and OnStart() methods. Triggers attached to these commands will execute the these methods.

Code

public class LetItSnowBehavior : Behavior<Canvas> {

 

    privateDispatcherTimer _gameLoop = newDispatcherTimer();

 

    public LetItSnowBehavior() {

        // Create Commands

        this.Start = newActionCommand(this.OnStart);

        this.Stop = newActionCommand(this.OnStop);

 

        // Init timer

        _gameLoop.Interval = newTimeSpan(0, 0, 0, 0, 10);

        _gameLoop.Tick += newEventHandler(gameLoop_Tick);

        _gameLoop.Start();

    }

 

    publicICommand Start { get; privateset; }

 

    publicICommand Stop { get; privateset; }

 

    privatevoid OnStart() {

        _gameLoop.Start();

    }

 

    privatevoid OnStop() {

        _gameLoop.Stop();

    }

 

    ...

You can use Expression Blend to attach triggers to the Commands. Select the LetItSnowBehavior object and open it properties. Click the + button for the Start property and select an EventTrigger. Select the 'buttonStart' as source and the 'Click' as event. You can even add multiple triggers to the command.

Set Triggers on LetItSnowBehavior in Expression Blend 3.0

You can download the code from here.

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.

Leave a comment

Blog comments

0 responses