Looking at Behaviors, the Class
May 16th, 2009 | View 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





May 17th, 2009 at 4:57 pm
[...] my previous post, I explained the basics of how to write a simple behavior. I concluded by mentioning that a [...]
May 19th, 2009 at 10:50 am
[...] >Looking at Behaviors, the Class [...]
June 5th, 2009 at 4:39 am
[...] my previous post, I explained the basics of how to write a simple behavior. I concluded by mentioning that a [...]
August 19th, 2009 at 4:02 pm
Great post, you forgot about weak references that make the whole process of attaching behaviors efficient.
November 25th, 2009 at 9:35 am
[...] >Looking at Behaviors, the Class [...]
March 8th, 2011 at 8:26 am
Your blog is fine. I just want to touch upon the design. Its too loud. Its doing means too much and it takes away from what youve acquired to say –which I think is actually important. I dont know when you didnt suppose that your words might hold everyones consideration, but you were wrong. Anyway, in my language, there usually are not much good supply like this.
March 8th, 2011 at 8:27 am
I was questioning what’s up with that weird gravatar??? I do know 5am is early and I am not wanting my greatest at that hour, however I hope I do not appear like this! I would however make that face if I’m requested to do one hundred pushups. lol Anyway, in my language, there are not much good source like this.
March 8th, 2011 at 8:54 am
Great post, and I?m pretty sure you?re doing exactly the right thing. Not absolutely certain, you understand, but pretty sure.
March 9th, 2011 at 3:04 am
Can I make a suggestion? I believe youve obtained one thing good here. But what for those who added a pair links to a page that backs up what youre saying? Or maybe you might give us something to have a look at, something that might connect what youre saying to something tangible? Just a suggestion. Anyway, in my language, there are usually not much good source like this.
May 3rd, 2011 at 8:14 am
Have you ever ever seo packages thought-about including seo packages more videos to your blog posts seo packages to keep the readers more entertained? I imply I simply learn by way of your seo packages complete article of yours and it was quite good but since I’m more of a visible learner,I discovered that to be more helpful effectively let me know the way seo packages it seems! I love what you guys are all the time up too. Such clever work and reporting! Keep up the nice works guys I’ve added you seo packages guys to my blogroll. This is a nice article thanks for sharing this informative information.. I will visit seo packages your blog usually for some latest post. Anyway, in my language, there will not be a lot good supply like this.
May 7th, 2011 at 3:17 pm
Great I’m truly loving this web template/theme for the website. It’s simple, yet effective. Very often it can be difficult to get that middle ground involving user friendliness plus visual appearance. I may state that you’ve done an great job with this. In addition, this blog starts very fast for me on Chrome. Excellent Blog site
October 12th, 2011 at 6:40 am
jimmy choo bridaland jimmy choo outlet Nike Lebron shoes andNike ZOOM LeBron new burberry replica burberry lebron 8 v2i want to look some pandora jewellery; pandora jewellery beads cheap nfl jerseys or jersey supply and religion jeans, you can leave a email to me! thank you! nike air max 2011white air maxnike griffey maxreligions jeanstrue religions jeans true religion jeans outletbears jersey blackhawks jerseyken griffey shoes air griffey maxken griffey jr shoes
air griffey max 2lebron 8 south beach,cheap Nike Air Max 2009cheap Nike Air Max 2010cheap Nike Air Max 2011cheap Nike Air Max 24 -7cheap Nike Air Max 360cheap Nike Air Max 87cheap Nike Air Max 88 Mencheap Nike Air Max 89 Mencheap Nike Air Max 90cheap Nike Air Max 91 Mencheap Nike Air Max 92 Mencheap Nike Air Max 93 Mencheap Nike Air Max 95
cheap Nike Air Max ACGcheap Nike Air Max Classic BWcheap Nike Air Max LTDcheap Nike Air Max Preview EU Mencheap Nike Air Max Skyline Mencheap Nike Air Max Tn Mencheap Nike Air Zenyth Mencheap Nike Griffey MaxNike Griffey max,Nike TN 2011,Nike air max skyline,bape shoes,Adidas Shoes 2011,Air Griffey Max Fury 2012,Air Jordan High Heels,black Air Jordan Shoes,Air Jordan Wool Boots
Jordan CMFT Max 12Leather,cheap Jordan Sandals,Ken Griffey Jr Jerseys,Ken Griffey Shoes 2011,Ken Griffey Shoes Womens,Nike ACG Boots sale,cheap Nike Aina Chukka,Nike Air 1/2 Cent Penny,Nike Air Foamposite One,Nike Air Max 2009 shoes,Nike Air Max 2010 shoes,Nike Air Max 24-7 shoes
white Nike Air Max 95,cheap Nike Air Max 95 Boots,Nike Air Max NM Nomo,Nike Air Max Uptempo 97,cheap Nike Heels for Women,Nike Ken Griffey Shoes
Nike TN 2011 shoes ,Nike Zoom Lebron shoes,Women’s Nike Dunk SB
cheap Pandora Necklacescheap Pandora Ringscheap Pandora Setscheap Pondora Packages
herve leger bandage dressesmoncler down jacketmoncler doudounesmoncler coatcheap moncler jacket
lebron 8 south beach
Nike ZOOM LeBron
Nike Lebron shoes
lebron 8 v2Nike Air Max LeBron 8 V2
detroit lions jersey
cheap authentic jerseys
cheap nfl jerseys
youth nfl jerseys
nfl jerseys wholesale
religion jeans outlet
true religion store
true religions
true religion billy
true religion men
men Bootcut jeans
men Flare jeans
men Skinny jeans
straight leg jean
true religion women
women bootcut jeans
women Flare jeans
cut off jeans shorts
girls skinny jeans
straight legs jeans
nike shox shoes
sb dunks
true religion joey
true religions jeans
true religion men jeans
cheap religion jeans
cheap true religion men jeans
true religion boys jeans
true religion billy mens
true religion cargo pants
true religion corduroy jeans
true religion capris
true religion joey jeans
cheap religion jeans
true religion mens skinny
True Religion Straight Leg
true religion womens jeans
true religion denim jeans
true religion denim shorts
true religion straight leg jeans
True Religion Wide Leg
skinny bootcut jeans
True Religion lizzy
True Religion joey rainbow
True Religion casey legging
True Religion lone star
True Religion stella
True Religion shirts for women
true religion brand
cheap true religion jeans
true religion brand jeans
true religion uk
moncler vest
moncler uk
moncler women jackets
moncler men jackets
October 21st, 2011 at 3:05 am
nfl team jerseys
team football jerseys
nfl jerseys on sale
buy nfl jerseys
football jerseys wholesale
replica soccer jerseys
cheapest nfl jerseys
nike air jordan retro
cheap gucci
cheap t shirts
cheap handbags
cheap sunglasses
jewelry for sale
cheap sandals
oakley sunglasses polarized
Tiffany Necklace
purses and handbags
Wholesale Cheap Jeans
air jordan retro
wholesalers for handbags
Bikini Swimwear
November 8th, 2011 at 8:12 pm
I used to be suggested this blog by means of my cousin. I am not positive whether this post is written by means of him as nobody else recognise such specified approximately my difficulty. You are amazing! Thanks!
November 11th, 2011 at 12:11 pm
Thanks for another magnificent article. Where else may just anybody get that kind of information in such a perfect way of writing? I have a presentation next week, and I’m at the search for such information.
November 11th, 2011 at 12:13 pm
Somebody necessarily lend a hand to make severely articles I’d state. That is the first time I frequented your website page and to this point? I amazed with the research you made to make this actual put up incredible. Fantastic activity!
November 15th, 2011 at 11:26 am
We invite you to visit our website. We offer the best flat in Wroclaw.
November 20th, 2011 at 4:19 am
You’re in reality a excellent webmaster. The website loading speed is incredible. It seems that you’re doing any unique trick. Also, The contents are masterwork. you’ve performed a wonderful activity on this subject!
November 21st, 2011 at 12:17 am
Hi there, I discovered your web site by the use of Google at the same time as looking for a related matter, your website came up, it appears to be like good. I’ve bookmarked to my favourites|added to my bookmarks.
November 22nd, 2011 at 3:26 am
That is really interesting, You are a very skilled blogger. I have joined your feed and look ahead to searching for extra of your great post. Also, I have shared your site in my social networks
November 23rd, 2011 at 8:56 am
http://www.gucci-shoes-uk.com/
November 23rd, 2011 at 12:12 pm
Hello very cool website!! Guy .. Excellent .. Superb .. I’ll bookmark your blog and take the feeds also?I am satisfied to search out so many useful information right here within the submit, we need develop more strategies on this regard, thank you for sharing. . . . . .
November 23rd, 2011 at 12:58 pm
Thanks , I’ve just been searching for information approximately this topic for a while and yours is the best I have came upon till now. However, what about the bottom line? Are you sure in regards to the supply?|What i do not realize is in fact how you are now not actually a lot more smartly-liked than you may be right now. You’re so intelligent.