Behaviors and Commands

May 17th, 2009     |     View 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:

behavior_summary

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:

 mycommandUI

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:

commandsWithEvents

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:

ica_commands

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 :)

View Comments to “Behaviors and Commands”

  1. Nigel Sampson Says:

    Thanks for an excellent post kirpua, a lot of the blend designer and behavior functionality is certainly not very discoverable at the moment.

    One thing I’d love to see changed before release is that Behaviors, Triggers and Actions inherit from FrameworkElement rather than DependencyObject, and therefore able to be the target for {Binding} expressions.

    An excellent example is that I’d like to be able to bind an ICommand exposed by my ViewModel (usng the MVVM pattern) to a behavior. Without binding the code becomes a lot more complicated.

    This is my top wishlist item to be changed in the beta, as the possiblities (especially with ElementName bindings) become a lot richer.

    Thanks

  2. kirupa Says:

    Hi Nigel,
    That is my number one request as well, but it is something that we will not be changing with our Behaviors in the Silverlight 3 timeframe unfortunately.

    As you noted, Behaviors inherit from DependencyObject in both WPF and Silverlight. WPF does support binding to DependencyObjects, and therefore, you do get binding support in the Behaviors you use in WPF projects.

    In Silverlight 3, because of the lack of data bindability with DependencyObjects, Behaviors do not get this functionality as well.

    From an architectural point of view, having Behaviors be DependencyObjects is better than them being FrameworkElements. While that is really unfortunate in the short run, hopefully this design in the long run will be better once/if Silverlight begins to support binding on non-FrameworkElements.

    In the interim, Pete Blois has blogged about a workaround for this: http://blois.us/blog/2009/04/datatrigger-bindings-on-non.html

    Thanks for the post, and do let me know if there are any other things you would like to see with Behaviors or Blend in general =)

    Cheers!
    Kirupa

  3. Nigel Sampson Says:

    Thanks, I’ve see that post from Pete and got the functionality that I’m after going, just a lot of wiring for simple behaviors and makes them very hard to unit test effectively

  4. Michael A. Smith Says:

    Would you mind posting the generated XAML?

  5. kirupa Says:

    Michael, I am unable to paste the XAML in the comments. If you can send me an e-mail kirupac[at]microsoft.com, I can e-mail you the XAML generated.

  6. Expression Blend and Design : Link Round-Up: Behaviors-Related Posts Says:

    [...] >Behaviors and Commands [...]

  7. aL Says:

    cool stuff :) but does this work in silverlight as well? i didnt think silverlight had ICommand?

  8. kirupa Says:

    aL – my above example is a Silverlight example actually :)

    Silverlight does have a version of ICommand: http://msdn.microsoft.com/en-us/library/system.windows.input.icommand(VS.95).aspx

    While this functionality may not be entirely on par with that of WPF, for what we are using ICommands for in Behaviors, it seems to do the job well.

  9. Silverlight Attached Behavior and Commands Says:

    [...] too many articles talking about attached behavior and commands. The best I found so far is from kirupa.com. He has a lot of good articles describing the details of behavior and command. Therefore, I am not [...]

  10. Terence Tsang Says:

    Hi, I have created a sample for Behavior and Command.

    http://www.shinedraw.com/designer-extensibility/silverlight-attached-behavior-and-command/

    Please take a look if you are interested.

  11. yiuaajkkfmuy Says:

    vrbihtqmayok

  12. Greg Says:

    Hello,

    I’m getting a “type or namespace name ‘ActionCommand’ could not be found…” build error.

    Where is ‘ActionCommand’ defined?

    Thanks

  13. Greg Says:

    Kirupa,

    I’m also getting a AG_E_PARSER_BAD_PROPERTY_VALUE
    error at run time when I commnet out the line with the ActionCommand stattement.

    Here is the code:

    public class GetDataAction : Behavior
    {
    public GetDataAction()
    {
    //this.MyCommand = new ActionCommand(this.MyFunction);
    }

    protected override void OnAttached()
    {
    base.OnAttached();
    AssociatedObject.MouseLeftButtonDown += OnMouseButtonDown;
    }

    protected override void OnDetaching()
    {
    base.OnDetaching();
    AssociatedObject.MouseLeftButtonDown -= OnMouseButtonDown;
    }

    private void OnMouseButtonDown(object sender, MouseButtonEventArgs e)
    {
    this.AssociatedObject.Effect = null;
    }

    public ICommand MyCommand
    {
    get;
    private set;
    }

    private void MyFunction()
    {
    MessageBox.Show(“Hello World”);
    }
    }

    Am I missing something obvious?

    Thanks

  14. Ray Blackwater Says:

    Very interesting blog post thank you for writing it I have added your blog to my bookmarks and will be back.

  15. Burma Liao Says:

    Hello,guys,your blog is really great! I like it.

  16. cabbage soup diet Says:

    Took me time to read all of the feedback, but I really loved the article. It proved to be very helpful to me and I am sure to all the commenters right here! It’s always good when you can not solely be informed, but in addition engaged! I’m positive you had pleasure penning this article. Anyway, in my language, there aren’t a lot good supply like this.

  17. link wheel Says:

    Awesome. Love the premise of the blog, but really, you had me at Bazinga. Looking forward to see your success increase. Maybe I can glean some inspiration from the ride.

  18. sim so dep Says:

    Please inform me it labored right? I dont want to sumit it once more if i should not have to! Either the weblog glitced out or i am an idiot, the second option doesnt shock me lol. thanks for an amazing blog! Anyway, in my language, there are usually not a lot good supply like this.

  19. eternity bands Says:

    I would love to find out more can you point me in the right direction to find more information?

  20. link building services Says:

    I was questioning link building services what is up with that bizarre link building services gravatar??? I do know link building services 5am is early and I’m not wanting my finest at that hour, but I hope I link building services don’t seem like this! I would nonetheless make link building services that face if I am asked to do a hundred pushups. lol link building services Anyway, in my language, there aren’t much good supply like this.

  21. Franke Sinks Says:

    Thanks for taking the time to discuss this, I feel strongly about it and adore knowing a lot more on this subject. If achievable, as you acquire experience, would you mind updating your blog with additional info? It’s extremely useful for me.

  22. Adrian Muwwakkil Says:

    Just, admirable what you might have done here. It truly is pleasing to appear you express through the heart along with your clarity on this considerable subject material may be simply looked. Outstanding publish and can search forward for your long run update.

  23. Doncaster Ecommerce Says:

    Hi, brilliant topic I have just joined your mailing list

  24. Seana Covernt Says:

    Hi there, just became alert to your blog through Google, and found that it’s really informative. I am going to watch out for brussels. I will be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  25. 154443 Says:

    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

  26. moncler clairy cher Says:

    This is really interesting, You are a very skilled blogger. I’ve joined your feed and look ahead to in search of more of your excellent post. Also, I’ve shared your website in my social networks

  27. jewelry for brides Says:

    A person essentially help to make severely posts I would state. This is the very first time I frequented your website page and up to now? I surprised with the analysis you made to create this actual publish amazing. Magnificent job!

  28. Gayle Camerano Says:

    You don’t seem to have a very good grasp of the concept of plagiarism-. top mmorpg,best mmorpg,what is mmorpg

  29. ナイキ Says:

    Love all the new cookies. Especially the different tree designs. You rock! As always!

Leave a Reply

blog comments powered by Disqus