A Colorful Explosion
June 21st, 2009 | 8 Comments
It has been a while since I have had some time to experiment with scripted movement, so I figure I will start with one I created a few hours ago. Simply hover over the yellow square to see a barrage of colorful circles zooming in on you:
The code for doing all of this seems substantial, but it is just many small lines of fairly straightforward code. I have a single AS Class file called ColorfulCircle, and the code inside it controls what each instance does:
- package {
- import flash.display.*;
- import flash.events.*;
- import flash.geom.*;
- public class ColorfulCircle extends MovieClip {
- var radians;
- var speed;
- var radius;
- var originalX:Number;
- var originalY:Number;
- static var colorArray:Array = new Array(0xFFFF33, 0xFFFFFF, 0×79DCF4, 0xFF3333, 0xFFCC33, 0×99CC33);
- public function ColorfulCircle() {
- originalX = this.x;
- originalY = this.y;
- setProperties();
- this.addEventListener(Event.ENTER_FRAME, flyCircleIn);
- }
- function setProperties()
- {
- speed = Math.ceil(5*Math.random());
- radius = 20*Math.random();
- radians = 0;
- trace(speed);
- this.scaleX = 0;
- this.scaleY = 0;
- var randomColorID:Number = Math.floor(Math.random()*colorArray.length);
- var myColor:ColorTransform = this.transform.colorTransform;
- myColor.color = colorArray[randomColorID];
- this.transform.colorTransform = myColor;
- this.alpha = 1;
- }
- function flyCircleIn(e:Event) {
- radians += Math.abs(speed/10);
- this.x += Math.round(radius*Math.cos(radians));
- this.y += Math.round(radius*Math.sin(radians));
- this.scaleX += Math.abs(speed/10);
- this.scaleY += Math.abs(speed/10);
- this.alpha -= Math.abs(speed/100);
- if (this.alpha < 0)
- {
- resetCircle();
- }
- }
- function resetCircle()
- {
- this.x = originalX;
- this.y = originalY;
- setProperties();
- }
- }
- }
Almost everything you see above has been covered in various tutorials on kirupa.com. The two most relevant would be Classes and Movie Clips and Changing Color in ActionScript 3.
You can download the source file for the above animation below, and as always, feel free to do whatever you want with it:
| Download Colorful Explosion Source (Flash CS4) | |
| Download Colorful Explosion Source (Flash CS3) |
If I have some time, I may write a tutorial about this in the near future.
Cheers!
Kirupa
Targeting Other Elements via the Blend 3 UI
June 6th, 2009 | 8 Comments
In an earlier post, I described how you can change what your EventTrigger and Action (based on TargetedTriggerAction) can target. You can get into various interesting scenarios where what your Action is attached to is not the element your Trigger is listening for events on, nor is the element your Action is attached to the one that gets affected by whatever the Action does.
What I have not done is described how you would actually be able to do this using the Blend UI. That seems kinda important! Let’s say you have an Action (which derives from TargetedTriggerAction) applied to a Button. If you select the Action and look over in the Properties pane, you would see something similar to the following image:
The two properties that allow you to target other elements are SourceName in the Trigger category and TargetName in the Common Properties category:
By default, both of these properties are set to target the Parent. Parent is the element your Action is applied to, but you can change what your element targets in two ways.
The Select Element Dialog
In the MIX release of our Blend 3 Preview, one approach was by hitting the little … button and launching the Select Element dialog:
The Select Element dialog provides you with a copy of your object tree with all visual elements displayed. The emphasis on “visual” is important because your object tree today displays non-visual content such as behaviors, and you will not be able to select them via the Select Element dialog.
This dialog is great for being able to pick from a large list of elements or to pick from an element whose name you know but cannot actually see on the artboard. For example, think of a circle whose opacity is set to be fully transparent. Unfortunately, these are edge cases. We didn’t want the only way to be able to target other elements to be one that was optimized for edge cases! To deal with this, shortly after MIX, we decided to add another way for you to be able to pick elements to target, and that is the Artboard Element Picker.
Artboard Element Picker
Like I briefly mentioned in the last paragraph, the Select Element dialog is primarily useful for a few edge cases. The most common case is one where you want to select an element that you have visible on your design surface. To help with this, we introduced the Artboard Element picker, and it can be accessed via the the bulls-eye icons you see inside the SourceName and TargetName properties:
When you click on either of these icons, you enter a special element selection mode where your mouse cursor changes to that of a bulls-eye, and you can move your mouse cursor over any element on the artboard to select it:
Notice that, now, I simply point and click at the element I want to target, and that is pretty convenient when what I want to target is clearly visible. If you have a lot of elements that possibly overlap, such as the four overlapping squares I have in my example, you can always hit the Ctrl key and click to display a menu of elements under the mouse cursor that you can select:
You also have the ability to use the Artboard element picker on the Object tree itself. You would think with the name of “Artboard Element Picker” you would be constrained to just the artboard, but you are not:
The cursor displays the cancel sign when you hover over areas outside of the Artboard or Object tree, so it isn’t possible yet to select other types of things you may want to target.
Conclusion
Hopefully, this post helped give you a glimpse of what we are doing to make it easier for you to use Behaviors by presenting you with two ways you can easily use the targeting functionality our API provides. There are other niceties that we’ve added for Behaviors that I will describe in some more detail shortly.
Thanks,
Kirupa
Behaviors and Commands
May 17th, 2009 | 11 Comments
In my previous post, I explained the basics of how to write a simple behavior. I concluded by mentioning that a behavior can actually be made to work with triggers. This is possible despite a Behavior having no real mechanism for a trigger to bury itself into. How is that possible? This post will explain how.
I may have lied a little bit. My previous explanations of Behaviors being solo-artists is not entirely accurate. While Behaviors can work independently without any external influence, unlike an Action, they can also be made to do certain things when certain conditions are met:

That is why the condition part of the original sentence is grayed out as opposed to completely .being removed.
Your Wish is My ICommand
If you want your behavior to be capable of being triggered, you can expose Commands (anything of type ICommand) to be the function that will get called. If you are confused about what I just wrote, don’t worry. Let’s write a behavior that demonstrates this. First, make sure your project has a reference to both the Microsoft.Expression.Interactions and Microsoft.Expression.Interactivity DLLs.
After you have done that, create a new Class file, and before you do anything else, add the following using statement:
- using Microsoft.Expression.Interactivity.Input;
Once you have done this, add the code to turn your class into a behavior:
- public class BehaviorWithCommand : Behavior<DependencyObject>
- {
- public BehaviorWithCommand()
- {
- this.MyCommand = new ActionCommand(this.MyFunction);
- }
- protected override void OnAttached()
- {
- base.OnAttached();
- }
- protected override void OnDetaching()
- {
- base.OnDetaching();
- }
- public ICommand MyCommand
- {
- get;
- private set;
- }
- private void MyFunction()
- {
- MessageBox.Show("Hello World");
- }
- }
Note that I call my behavior BehaviorWithCommand, so be sure to rename your class name and constructor appropriately instead of using my name if you copy/paste. Save and build your project to make sure everything works and nothing is complaining.
Looking at the Blend 3 UI
Go ahead and apply this Behavior any element in your Silverlight or WPF application. Once you have added it to something, select this behavior and look at what is displayed in your Properties Inspector:
Notice that you now see a category called MyCommand, the name of your ICommand property specified in code.
From this category, on the top-right corner, you can use the plus button to add the triggers that will invoke your MyCommand command:
This UI may be new to you if you’ve never played with Behaviors that expose Commands. With commands, notice that I am not stuck with just one Trigger. I am able to add multiple triggers that can each call the same MyCommand function, and just like with Actions, I have the ability to modify the properties of my trigger as well!
How this Works Behind the Scenes
What you see in the Blend UI is a major abstraction of what goes on behind the scenes. To help you understand what is happening better, the following diagram gives you an overview of how commands and Behaviors work together to give you Action-like abilities:
Notice that your behavior exposes a command, and there exists an Action called InvokeCommandAction that does nothing but, as it name implies, invoke commands. Since this is an Action, you have the abilities to set triggers on it. All you ever see in the Blend UI is the Command and the Triggers that you want to set on it. Behind the scenes, we map your trigger to the InvokeCommandAction that is associated with the Command.
This means the trigger has no knowledge of the behavior. They are completely decoupled and fit with the self-contained, solo model that I have been describing about Behaviors for the past few posts. Because they interact with Actions that, in turn, interact with Commands exposed by the Behavior, you have the ability to have our behavior do things with some external input just like you can with Actions.
Conclusion
All right. This wraps up my current series of posts describing Behaviors themselves. You may find yourself wondering why you would ever want to use a Behavior when Actions just seem much easier to use and conceptually understand. The answer is, for the most part, rarely.
Unless you want the ability that Behaviors have where you can internally manage state independent of being tied to a trigger, you will find a Trigger and Action pair to be your best friends as you navigate through this sea of interactivity. For a class of interactions, especially those involving state, having a Behavior handy does not hurt either though.
Cheers!
Kirupa
Looking at Behaviors, the Class
May 16th, 2009 | 3 Comments
In my earlier article a few weeks ago, I described the basics of Triggers and Actions. Triggers and Actions satisfy your standard, run-of-the-mill, cause and effect condition where something happens when you do something:

In this post, I am going to talk about the third leg in our three-legged Behaviors table, and it is a behavior itself. A behavior is a bit different than a trigger an action. Where triggers and actions work very closely with each other to have something happen, a behavior is the lone ranger that does not depend on anybody else.
Similar to your trigger and action, a behavior has the ability to do something when it is asked to do something. Unlike a trigger and action, though, a behavior also has the ability to do something whenever it wants to without any external notification from a trigger or trigger-like item.
If I had to redraw the “When ___ happens, do ___” sentence for a behavior, it would be as follows:
The entire half where a condition needs to be met before something happens is optional. Let’s take a look at the following example where I have a behavior that randomizes the positions of elements inside a Canvas automatically:
- public class RandomizeLayoutBehavior : Behavior<Canvas>
- {
- private Random positionRandom;
- public RandomizeLayoutBehavior()
- {
- positionRandom = new Random();
- }
- private void RandomizeContents()
- {
- Canvas parentCanvas = this.AssociatedObject;
- parentCanvas.Loaded += new RoutedEventHandler(parentCanvas_Loaded);
- }
- protected override void OnAttached()
- {
- base.OnAttached();
- RandomizeContents();
- }
- protected override void OnDetaching()
- {
- base.OnDetaching();
- }
- private void parentCanvas_Loaded(object sender, System.Windows.RoutedEventArgs e)
- {
- Canvas parentCanvas = sender as Canvas;
- if (parentCanvas != null)
- {
- // Iterating through each child element inside the canvas and giving it a random position
- foreach (UIElement element in parentCanvas.Children)
- {
- int xPosition = positionRandom.Next((int) parentCanvas.Width);
- int yPosition = positionRandom.Next((int) parentCanvas.Height);
- Canvas.SetLeft(element, xPosition);
- Canvas.SetTop(element, yPosition);
- }
- }
- }
- }
To make this example work, make sure your behavior is placed on a Canvas that a.) has child elements, and b.) has a set Width and Height. In other words, if your Canvas’s width and height are just Auto, this will not work.
In case you are curious, here is how the Object Tree in Blend looks like with my RandomizeLayoutBehavior applied:
The behavior is pretty straightforward. When your app runs, since it is attached to your Canvas, it looks at each of the Canvas’s children and randomly positions them in a different location.
I am not going to be describing the specifics of this behavior. Instead, the more interesting thing to look at is what is needed to basically create your behavior. The basics of what you need for a behavior are as follows:
- public class Behavior1 : Behavior<DependencyObject>
- {
- public Behavior1()
- {
- // Insert code required on object creation below this point.
- }
- protected override void OnAttached()
- {
- base.OnAttached();
- // Insert code that you would want run when the Behavior is attached to an object.
- }
- protected override void OnDetaching()
- {
- base.OnDetaching();
- // Insert code that you would want run when the Behavior is removed from an object.
- }
- }
You need to extend your class by the Behavior type that we provide as a part of the Microsoft.Expression.Interactivity.dll, and once you have done that, just override the OnAttached and OnDetaching methods.
The code you place in OnAttached is what causes your behavior to run. By default, that is when your behavior is initialized. By not being tied to running only when a trigger tells you to, you have the ability to create interactions that are bit more involved or store state.
Conclusion
Hopefully this post gives you a good overview of how to write your own Behavior. The behavior I showed you in this post runs by default when it gets attached to the parent object. Not all behaviors work that way, and they can actually be made to do something at specific times using a trigger!
In a future post, I will describe how to create a behavior that exposes functionality to be associated with triggers.
Cheers!
Kirupa
Looking at Triggers and Actions
April 27th, 2009 | 7 Comments
Like I’ve mentioned several times earlier, behaviors in Expression Blend 3 are made up of extensible Triggers, Actions, and Behaviors. What I really have not done is explain in greater conceptual detail what each of those pieces do and how far you can push our default implementation. In this post, let’s fix that by giving Triggers and Actions their long-awaited detailed overview.
In a Nutshell
If I had to sum up what triggers and actions do, the following sentence is it:
Pretty simple, right? Let me take a few steps back and look at a few examples. When I flip on a light switch switch, the light needs to turn on. When I click on a button, a sound needs to play. When I hit a certain time, the application should close. What I have just described are simple cause-and-effect relationships, and in a nutshell, Triggers and Actions are nothing more than digital manifestations of them. The cause (When) is controlled by the Trigger, and the effect (Do) is controlled by the Action:
All of the examples involving Actions that I have shown you over the past few blog posts follow a similar pattern:

In the Blend UI, we suppress a lot of the details for you. You only drag and drop an Action onto an element, and the trigger is either automatically set as specified by the Action, or you can set it yourself. That seems simple…sort of!
Sneaky Like a Fox
What makes Triggers and Actions more interesting is how sneaky they actually can be. When you drag an Action onto an element in Blend, your Action is parented under this button:

What is worth looking into is what the Trigger and Action are looking at, and let’s assume the Trigger we are looking at is an EventTrigger. Dropping an Action onto the above button will set the Trigger’s source to that of the button itself, and it will also set your Action’s target to be that of the button as well:
What you have the ability to do is set the Source to some other element besides your button. Let’s say you have a checkbox you want to set as your EventTrigger’s Source instead.
With our current Behaviors implementation, you can simply change the Source of your Trigger to that of your checkbox very easily by setting the Trigger’s SourceName property to that of your checkbox:
This means that your Action will do something when the event you are listening for on your CheckBox fires.
You’ve just seen how we can set the source of a trigger, our EventTrigger, to that of another element besides the one your Action is parented under. To make things a bit more interesting, you also have the ability to target your Action to affect an element other than the one you are parented under as well!
If your Action inherits from TargetedTriggerAction instead of just TriggerAction, you gain access to the TargetName property that allows you to specify which element you want your Action to affect. So you can have something such as the following:
Your Action is parented under the Button, but your EventTrigger is actually listening for events from a CheckBox. When the trigger fires, your Action does its thing on a blue rectangle that it is targeting.The actual Button is merely the Action’s host and it derives no benefit from it because neither the Action nor the Trigger care about it. Sad, isn’t it?
Rationale Behind This
Right now, you are probably wondering why we allow you to do something like this. It isn’t as if you have to manually modify XAML for this. We provide UI today that allows you to easily do this. The reason has to to do with different approaches individuals have on how the relationship between a trigger and Action should work.
I tend to like the following approach where my Action is on the element that will be the Source of my trigger:
This is known as the Tell approach because I am telling my Action to affect something else. The other approach is known as Listen, and it is where you place your Action on the element that is being affected as opposed to the Source of the trigger:
There is no right or wrong way to approach how you wire up your Triggers and Actions. The thing to note is that our Behaviors API is flexible enough to support both, and our UI makes it easy for you to pick either Listen or Tell without having to do anything crazy.
Cheers!
Kirupa
:
The Draw Yourself Contest is Now Over!
April 20th, 2009 | No Comments
Voting for the Draw Yourself Contest ended a few days ago, and the winning entries are from JUNASIPARK, GrandMasterFlash, and TheBruce.
A big thanks to all of the contestants, but also to all of the judges (adam, nokrev, iamthejuggler, templarian, and me).
There will be more contests in the near future, but until then, this blog will return to the usual Flashing, .NET’ing, and the usual assortment of other random topics.
Cheers!
Kirupa
Behaviors : Writing Your Own Triggers
April 9th, 2009 | 4 Comments
In my previous posts, I briefly discussed what behaviors are and how to use them. Let’s now talk about writing your own behaviors. Behaviors is a catch-all word that describes behaviors, actions, and extensible triggers. For an overview of what all three mean, check out Jeff Kelly’s blog post as well as Christian Schormann’s two overview blog posts on this topic.
Because there is already some great material out there on the basics of behaviors, I am going to shift gears and explain how to write behaviors. First up, I am going to go into some detail in this blog post by showing you how to write your own Trigger!
What are Triggers?
Like I mentioned earlier, behaviors (much like a famed group of musketeers!) are made up of three components – the Behavior, the Action, and the Trigger. The Trigger is really the catalyst for causing an Action and indirectly a Behavior to actually do something.
Examples of triggers range from something common such as an EventTrigger that fires an Action when a mouse or keyboard event is raised to something fun like a CollisionTrigger that fires an Action when two objects collide with each other. The thing to note is that, much like everything in our implementation of behaviors, Triggers are extensible. You can easily create your own kind of crazy triggers…such as what I am going to show you next.
The DoubleClick Trigger
One common gesture that I miss in Silverlight is the ability to double click. You can always click once, but if I want an Action to do something with a double click, I will have to provide this functionality myself. The below code shows you what a sample double click implementation looks like:
- namespace TriggerTest
- {
- public class DoubleClickTrigger : TriggerBase<UIElement>
- {
- private int count = 0;
- private DispatcherTimer _timer;
- public int DoubleClickSpeed
- {
- get { return (int)GetValue(DoubleClickSpeedProperty); }
- set { SetValue(DoubleClickSpeedProperty, value); }
- }
- public static readonly DependencyProperty DoubleClickSpeedProperty = DependencyProperty.Register("DoubleClickSpeed", typeof(int), typeof(DoubleClickTrigger), new PropertyMetadata(500, DoubleClickSpeedChanged));
- private static void DoubleClickSpeedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- // Code for dealing with your property changes
- }
- protected override void OnAttached()
- {
- base.OnAttached();
- this.AssociatedObject.MouseLeftButtonDown += new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown);
- }
- void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- if (count == 0)
- {
- _timer = new DispatcherTimer();
- _timer.Interval = new TimeSpan(0, 0, 0, 0, DoubleClickSpeed);
- _timer.Tick += new EventHandler(ResetCount);
- _timer.Start();
- }
- count++;
- if (count >= 2)
- {
- this.InvokeActions(null);
- }
- }
- void ResetCount(object sender, EventArgs e)
- {
- count = 0;
- _timer.Stop();
- }
- protected override void OnDetaching()
- {
- base.OnDetaching();
- this.AssociatedObject.MouseLeftButtonDown -= new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown);
- }
- }
When this trigger is used on an Action, double clicking on the element your Action is listening to will cause it to fire. I have a property called DoubleClickSpeed that allows you to adjust how quick or slow the double click needs to be before your two clicks are registered as a double click.
Looking Briefly at the Code
While it seems like a lot of code, what I am doing is actually pretty straightforward. Instead, I am going to remove all of the double click specific functionality and just show you the bare minimum of what you need to create a trigger:
- public class Trigger1 : TriggerBase<DependencyObject>
- {
- protected override void OnAttached()
- {
- base.OnAttached();
- }
- protected override void OnDetaching()
- {
- base.OnDetaching();
- }
- //
- // To invoke any associated Actions when this Trigger gets called, use
- // this.InvokeActions(o)
- //
- }
Notice that I am extending my class from TriggerBase – a type that is provided for you inside Microsoft.Expression.Interactivity.dll. Once I extend from the TriggerBase class, all I really have left to do is just override the OnAttached and OnDetaching methods like I show above.
Think of your OnAttached and OnDetaching methods like the constructor and destructor of your class. Anything you want initialized when the Trigger gets associated with an Action, be sure to specify it in the OnAttached method. Anything you want removed or cleaned up when the Trigger is no longer being associated with anything, be sure to put that in your OnDetaching method.
Finally, to actually have your trigger fire, though, you need to make a call to the InvokeActions method. Only when InvokeActions gets called will any Actions associated with this Trigger be notified to do whatever it is they do. My DoubleClickTrigger is simply an extension of the few lines of code that make up a barebones trigger starting point.
Using Triggers in Blend
Once you have written your trigger, using them in your own project is pretty straightforward. Draw a simple element, such as a rectangle, and drag and drop an Action on to it. If you don’t have any Actions you can use, feel free to borrow some from your peers on the Expression Gallery’s Behaviors category.
When you apply an Action to an element and select it, your Properties Inspector will display the current trigger applied as well as any properties your Action may expose. You can click the New button inside the Triggers category to display a dialog that allows you to pick your DoubleClickTrigger:
Once you have selected your DoubleClickTrigger, click OK to accept it as the Trigger for your Action. After you do that, your Trigger category will display the things relevant to you customizing your DoubleClickTrigger:
Well, that is all there is to it. Hopefully this post gave you a quick overview of how to write your own Triggers for this extensible family we call Behaviors.
Update: Thanks to a comment from Bart, I made a simple change to the code.
Cheers!
Kirupa
Vote for the “Draw Yourself” Contest Entries
April 9th, 2009 | No Comments
A couple of days ago, we just wrapped up the Draw Yourself contest. That means, voting is now under way where you get to pick which of the submitted entries you like the most. If you haven’t had a chance to vote, click here to do so.
Below you will find a scaled down version of all of the entries:
If you did not get a chance to participate in this contest, don’t worry. We will have more contests in the near future. If you have any ideas for contests you would like to see, be on the lookout for threads in Random asking for your opinion.
Cheers!
Kirupa
Dependency Property Generator Article
March 29th, 2009 | No Comments
A few weeks ago, I wrote a dependency property generator for Silverlight. Overall the feedback in my inbox has been great, but one thing many of you wanted was to learn more about what to do once the code gets generated. At first glance, it may not be obvious where exactly to paste the code or what the meaning of the “Owning Class” really means.
To help address some of those issues, I decided to promote my generator from the blog and put them on the main site itself: http://www.kirupa.com/blend_silverlight/dependency_property_generator.htm
Not only do you still have the dependency property generator, you also have a fair amount of textual information that can help answer some of those open questions a bare code snippet may not provide hints for.
Cheers!
Kirupa
I Want to be a Twit Too!
March 24th, 2009 | 5 Comments
If you’ve been my Facebook friend for any period of time, you probably know that I am not the biggest fan of Twitter. I just don’t get what makes it so fascinating.
Anyway, after much coercion by various peers (who themselves are complete twits*) over the past few months, I’ve decided to give Twitter a shot and see how things go:
I’ll try to keep my tweets related to boring technology stuff (with the occasional update on what I’ve had for lunch), so feel free to follow along at: http://twitter.com/kirupa
Cheers!
Kirupa
* Most aren’t complete twits. They divide their time with Facebook as well.




