This is a mirror of official site: http://jasper-net.blogspot.com/

Understanding the Role of Commanding in Silverlight 4 Applications

| Tuesday, March 22, 2011
I’ve had the opportunity to give a lot of presentations on the Model-View-ViewModel (MVVM) lately both publicly and internally for companies and wanted to put together a post that covers some of the frequent questions I get on commanding.  MVVM relies on 4 main pillars of technology including Silverlight data binding, ViewModel classes, messaging and commanding. Although Silverlight 4 provides some built-in support for commanding, I’ve found that a lot of people new to MVVM want more details on how it works and how to use it in MVVM applications.

If you're building Silverlight 4 applications then you've more than likely heard the term "commanding" used at a talk, in a forum or in talking with a WPF or Silverlight developer. What is commanding and why should you care about it? In a nutshell, it's a mechanism used in the Model-View-ViewModel (MVVM) pattern for communicating between a View (a Silverlight screen) and a ViewModel (an object containing data consumed by a View). It normally comes into play when a button is clicked and the click event needs to be routed to a ViewModel method for processing as shown next: 

clip_image002_thumb_53244634.jpg

When I first learned about the MVVM pattern (see my blog post on the subject here if you're getting started with the pattern) there wasn't built-in support for commanding so I ended up handling button click events in the XAML code-behind file (View.xaml.cs in the previous image) and then calling the appropriate method on the ViewModel as shown next. There were certainly other ways to do it but this technique provided a simple way to get started. 

private void Button_Click(object sender, RoutedEventArgs e)
{
    //Grab ViewModel from LayoutRoot's DataContext
    HomeViewModel vm = (HomeViewModel)LayoutRoot.DataContext;
    //Route click event to UpdatePerson() method in ViewModel
    vm.UpdatePerson();
}

While this approach works, adding code into the XAML code-behind file wasn't what I wanted given that the end goal was to call the ViewModel directly without having a middle-man. I’m not against adding code into the code-behind file at all and think it’s appropriate when performing animations, transformations, etc. but in this case it’s kind of a waste.  What's a developer to do? To answer this question let's examine the ICommand interface. 

Posted via email from Jasper-net

0 comments: