Reverse ICommands for MVVM

Posted by Rishi on 07-Jan-10 5:13 AM - Comments (10)

One of the problems with MVVM designs is the inability of the ViewModel to singularly effect change(s) within the View; yes, you can use data-changes through data-binding as a crude-bludgeon, but I'd rather have the right tools for the right job. And that is where Reverse ICommands come in, they allow you to execute an ICommand in your ViewModel and have it trigger a set of specified action(s) in the View - the reverse taxonomy speaks to the fact that reverse ICommands targets your View rather than the ViewModel.

AvatarView the sample application here and the source code is also available at Codeplex.

Design: Extends ICommand

In working terms reverse commands are ICommands that acknowledge when they execute - the acknowledgement gives us the ability to respond to them from within the View. Implementation wise, see the IReverseCommand interface, we only add a CommandExecuted event to the ICommand definition.

IReverseCommand

The other part to reverse commands is the ReverseCommandTrigger behavior, to which we can bind our reverse command and associate one or more Trigger Actions to invoke when the associated command is executed. For example, in the Silverlight Console Project the Console definition has a "Beep" method to which we have to make a beeping sound (obviously) - however, the beeping sound playing control lies in our View and we have to trigger it from our ViewModel. So using reverse commands, first in our ViewModel we declare the reverse command property, initialize it to do nothing in our ViewModel (though you can have it do something else), and execute it when asked to beep (the OnBeep method), have a look:

   1: // we define our reverse command as a property in our ViewModel
   2: public IReverseCommand BeepReverseCommand { get; private set; }
   3:  
   4: // and we set it up like this in our ViewModel
   5: BeepReverseCommand = new ActionCommand(() => { });
   6:  
   7: // we handle Beep call request in our ViewModel and Execute the reverse command
   8: protected override void OnBeep() {
   9:     BeepReverseCommand.Execute();
  10: }

Then in our View, the XAML features the Media Element control and a reverse command Trigger which plays the media:

   1: <!-- We define the sound playing Media Element -->
   2: <MediaElement x:Name="beepAudioMedia"
   3:     Source="/Resources/beep.wma" Volume="1" AutoPlay="False"/>
   4:  
   5: <!-- And we set up Reverse Command Trigger to play the media -->
   6: <nTriggers:ReverseCommandTrigger ReverseCommandBinding="{Binding BeepReverseCommand}">
   7:     <Behaviors:PlayMediaElementAction TargetName="beepAudioMedia"/>
   8: </nTriggers:ReverseCommandTrigger>

As you can see, the workflow of reverse commands is very similar to regular ICommands, except we reverse the receiver/sender roles - the ViewModel here explicitly triggers the Command by calling execute, and the View hooks up Actions to go with the execution of the Command. Also note, all the ICommand implementations in nRoute are reversible because they all implement IReverseCommand - so you can use them as regular and/or reversed commands.

Usage: An Example

The attached sample application is really very simple, it basically has three screens and we control the flow and interaction between them from our ViewModel using ICommands and IReverseCommands. The three screens are realized as Visual States on the View and, as shown below, the Home Screen helps get a user's response to a question, the Trailer Screen shows a movie trailer and the Message Screen self-descriptively shows a message.

 SampleAppViewViewModel

Within our ViewModel, the Home command navigates to the Home Screen, the PlayPause command toggles the pause-state of the trailer, the Response command gets the user's response from the Home Screen. The reverse commands help navigate between the screens by changing the Visual State of the View, and the play/pause reverse commands do as they suggest. The idea here is to show how from within the ViewModel we can, without direct dependencies, control the View - like when we navigate away from the Trailer Screen we pause the movie and when we enter into the Trailer Screen we resume the movie all from the ViewModel. Even the playing state of the trailer is kept within the ViewModel, similarly when we get the initial question's response the ViewModel decides which screen to navigate to, and if appropriate which message to show. All this builds on the separation of concerns principle, and though the functionality here is petty, the application of ICommands and IReverseCommands helps us manage the View-ViewModel interaction in both directions.

Summary: ICommands Reversed

ReverseCommandsModel

Per the principles of MVVM, in SL, we have two primary ways of communication between the View and the ViewModel - one, data-changes signifiers that rely on data-binding, and two, ICommands based invocation of actions from the View. Data-changes as a mechanism for inter-communication works for some cases, but in other cases it is too implicit and imprecise, and this is where ICommands weigh in - they are good for explicit, loosely-coupled, and strongly-typed invoking of actions. However ICommands are one-way creatures designed to be invoked from the View, and handled within the ViewModel.

On the other end, invoking of actions from the ViewModel-to-View is the functional gap that IReverseCommands fulfill, and just like ICommands they are explicit, precise and strongly-typed. Further, as with ICommands you also get ICommands-associated functionality like can-execute checks, enabling-disabling of ICommands, and explicitly defining of dependencies like in nRoute. Now, technically there might be many ways to achieve what reverse commands do but for me the fact that here we have a loosely-coupled setup which makes use of the binding infrastructure in SL and extends one the primary communication mechanism to work in reverse is a handsomely meriting solution.

You can view the Sample App here,
you can download the Sample App source-code here,
and read about the rich support for ICommands in nRoute here.

Comments (10) -

Michael Washington
Michael Washington United States
on 13-Dec-09 11:32 AM
Very well written (also a nice easy to read blog layout). The commanding implementation you have created makes sense to me.

Rishi
Rishi
on 31-Dec-09 1:38 AM
@Michael, thanks. In my experience the issue of having the View react to the VM instruction precisely (as in other than through data-changes) has been a sore point and with Reverse Commands we can overcome that limitation. A very simple example of this is having the View perform navigation - by its very nature navigation is a very View-specific task, but one that can be initialized by the VM - and so by using Reverse Commands we can have that specifically declared and executed.

fadda
fadda United States
on 25-Mar-12 8:44 PM
Thank you for a great time viewing your website. It’s truly a pleasure knowing a site like this packed with excellent information.
<a href="pakpoliticalforum.co.cc/forum.php">pakistani forum</a>

Brian
Brian United States
on 17-Apr-12 4:08 PM
nice!

Cheap NFL Jerseys
Cheap NFL Jerseys People's Republic of China
on 04-May-12 7:33 PM
Nike rolled out its new uniforms for all 32 NFL teams Tuesday at a gala celebration in New York. Cheap NFL Jerseys Network's Michelle Beisner was on hand as stars from around the league modeled the new duds, kept (mostly) under lock and key in the weeks leading up to Tuesday's launch.
<a href="http://www.cheapnfljerseys4us.com">Cheap NFL Jerseys</a>
<a href="http://www.cheapnfljerseys4us.com">Cheap Jerseys</a>
<a href="www.cheapnfljerseys4us.com/...10.html">New York Giants Jerseys</a>
<a href="http://www.cheapnfljerseys4us.com">NFL football Jerseys</a>
<a href="http://www.cheapnfljerseys4us.com">NFL Jerseys Wholesale</a>
For those concerned about drastic changes, fear not. Beisner confirmed the majority of uniforms received tweaks to fabric and composition, but Nike managed to have a little fun with the Seahawks. Seattle's uniforms received the most drastic makeover of all, with a revamped helmet logo and revised color and design schemes for the team's home and away Cheap jerseys.

throw back jerseys
throw back jerseys People's Republic of China
on 06-May-12 6:33 PM
Footballing months will be to use and thus star roller skating selects has become a good

flaming online business all over again![url=http://www.goodlynfljerseys.com/]throw back

jerseys[/url] In the event you starving keep in mind that pleasurable couple of years of an

Football ultimately the actual Superb Tank, you happen to be a absolutely pure blood vessels

rugby supporter![url=http://www.goodlynfljerseys.com/]cheap nba jerseys[/url] And if you're

never pleased entertaining for that bleachers of a popular club and desires to go made by

distraction using the exception cheap nfl jerseys your large fun regarding experiencing a,

therefore understand little league gambling and you might take on a increased exhilarating

dump[url=http://www.goodlynfljerseys.com/]personalized nfl jerseys[/url]!If these kinds of

somewhat of a blur in your case, now discover usually the commercial baseball selections

business enterprise therefore, you don't just exclusively devote your instalments with

searching for those individuals pricy airfare tickets but additionally obtain way merely by

engaging into fitness bets. On the other hand, gambling without using a lot of experiences

is one method about missing all earnings.

In the event you savvy, you will not basically mindlessly perform the

[url=http://www.goodlynfljerseys.com/]cheapest nhl jerseys[/url] probabilities otherwise

phase arises with consultants or you'll purely have an entirely dupe. Look around likewise

and enquire of assistance through the gambling enthusiasts authentic nfl jerseys .Can you

pick the right class alternatively find the accurate prospects? You can find

[url=http://www.goodlynfljerseys.com/]cheap baseball jerseys[/url] actions the process

regarding and if you are neophyte towards accomplishing this element its advisable to search

for their recommendations. A brief little search the web think that numerous details for

specialists along with individuals might possibly enhanced the idea opposite side among

gamers. These organizations have a very good pond regarding professional tipsters may very

well[url=www.goodlynfljerseys.com/nba-jerseys-c-23.html]swingman jerseys[/url] large

success rates and can definitely money-back guarantee the dollars may acquire a substantial

cash. Many handicapping providers are usually all on the web.
S

Guantee that before you actually arrange your hard earned dollars underneath the good the

right bets remedies company[url=www.goodlynfljerseys.com/nba-jerseys-c-23.html]nba

personalized jerseys[/url] that you simply understand how it any will work. Given that, it

must be diagnosed just as one expenditure. Skills consistent they're surely together with

additional gains that you can get through. Examine forums and in addition running forums

within tennis estimations. Try it out using their complimentary randomly chooses and wait to

determine[url=www.goodlynfljerseys.com/nba-jerseys-c-23.html]nba throwback jerseys

[/url] the successfully winning quantity along with program. It is almost always harder to

distinguish popular features of that will amazing advantages wagering business however it

want using our on-line world great results . a founded online business as well as

representative, you are able to an individual's making a bet background insight business

gamblers.As well as the profit,[url=www.goodlynfljerseys.com/mlb-jerseys-c-21.html]

baseball jerseys cheap[/url] the amount of your power are you prepared to fork out

concerning this Being bold from banks and loans, you cannot simply permitted this to number

of investment property clearly take an interval.

Earn Income
Earn Income United States
on 10-May-12 2:21 AM
I want to try reverse Icommands for MVVM, but don't know which tool you are suggesting here. Can you please tell me the name of the tool that you use here for reverse ICommandds method.

cheap designer bags
cheap designer bags United States
on 10-May-12 2:53 AM
Your website can be quite valuable. Thanks a great deal for giving many handy subject matter. I have bookmark your blog page internet site and will be lacking doubt coming back again. When once again, I appreciate all of your perform as well as comeing right here to communicate with me. BTW do you want to see Replica designer handbags Online, and choose the best bags image, Hermes bags and Louis Vuitton bags, they are awesome like you website, and also may be you like Parada handbags on sale. thank you.
www.luxury-bagstore.com/...scale-m93772-p-395.html
www.luxury-bagstore.com/...m93159-olive-p-402.html
www.luxury-bagstore.com/...abbia-m93499-p-420.html

business directory
business directory United States
on 12-May-12 4:52 PM
Yet another great post. You know, I am truly happy I came across this. I'll tweet your blog so my buddies can read this too!

Air Jordan Spizikes
Air Jordan Spizikes People's Republic of China
on 14-May-12 1:24 PM
Air Jordan Spizikes www.nikejordannew.com/air-jordan-spizikes.html

Gams and car games free to play
Gams and car games free to play United Kingdom
on 15-May-12 11:53 AM
Always play just the best http://www.carracinggamesonline.org car racing games and car games online. Avatar or games...? FOr me games,games online , always !

chy
chy People's Republic of China
on 16-May-12 9:10 PM
http://www.cheapchristiansandals.net

Pingbacks and trackbacks (9)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading