Cross-Training in Silverlight & Flex–MVVM vs Presentation Model

December 29th, 2010

More Cross-Training in SIlverlight and Flex

Shout it

This is probably my favorite topic in this Silverlight/Flex series.  In the Silverlight world, I have written extensively about the MVVM (Model-View-ViewModel) – a separated presentation pattern for stateful clients (like Rich Internet Applications).  When I got into Flex, I was shocked to find out how easy the pattern was to implement.  Developers in the Microsoft space call it MVVM but it was coined by Martin Fowler many years previous as Presentation Model.  I will use these terms interchangeably but mostly refer to MVVM when explaining the SIlverlight story and Presentation Model when explaining the Flex story.

If you do a Google search today for “MVVM and Flex”, the first post is by somebody who claims that MVVM is not a good fit for Flex.  I couldn’t disagree more.  Out of the box, the Flex framework makes it much easier to implement a Presentation Model than similar MVVM implementations in Silverlight.  That is not to say that there aren’t good third-party libraries that make it easier in Silverlight, but without any help, it is easier to do in Flex. 

I will show some examples and they should speak for themselves.

MVVM in Silverlight

In the MVVM pattern, there are two particular interfaces that are interesting to know:

  • INotifyPropertyChanged – an interface that lets ViewModels notify the UI when a property changes
  • ICommand – an interface that allows the UI to execute code on the ViewModels

Lets say we have a simple application where the model is excluded because it is not relevant to what I am trying to show.  The behavior is simple: when the user presses a button, read the text in the input field and output “Hello <input>”.  A simple implementation of the view might look like this:

    <local:ViewModel x:Key="ViewModel" />

<Border BorderThickness="5" CornerRadius="5" DataContext="{StaticResource ViewModel}"
        BorderBrush="Black" Height="Auto" Width="Auto">
    <StackPanel Orientation="Horizontal">
        <TextBox Width="100" Margin="3" Text="{Binding Input, Mode=TwoWay}" />
        <Button Content="Say Hello" Margin="3" Command="{Binding SayHelloCommand}" />
        <TextBlock Margin="3" VerticalAlignment="Bottom" Text="{Binding Output}" />

The ViewModel to support that logic looks like this:

public class ViewModel : INotifyPropertyChanged
    public string Input { get; set; }

    private string _output = string.Empty;
    public string Output
        get { return _output; }
            if (_output == value)

            _output = value;

    public ICommand SayHelloCommand { get; private set; }

    public ViewModel()
        SayHelloCommand = new DelegateCommand(SayHello);

    private void SayHello()
        Output = "Hello, " + Input;

    protected void RaisePropertyChanged(string propertyName)
        var handlers = PropertyChanged;
        if(handlers != null)
            handlers(this, new PropertyChangedEventArgs(propertyName));

    public event PropertyChangedEventHandler PropertyChanged;

public class DelegateCommand : ICommand
    private readonly Action action;

    public DelegateCommand(Action action)
        this.action = action;

    public bool CanExecute(object parameter)
        return true;

    public void Execute(object parameter)

    public event EventHandler CanExecuteChanged;

This example, admittedly, is a bit hyperbolic.  It includes everything you need to write a ViewModel from scratch.  In reality, the DelegateCommand is written once and reused.  In addition, most people will at least abstract the RaisePropertyChanged and PropertyChanged code by moveing it to a ViewModelBase class.  On that note, there are several third-party frameworks for making MVVM more pleasant in Silverlight.  I wrote one of those helpers, called ViewModelSupport.  Using the powerful, somewhat magical base class, the previous code can be re-written as:

public class ViewModel : ViewModelBase
    public string Input
        get { return Get<string>("Input"); }
        set { Set("Input", value); }

    public string Output
        get { return Get<string>("Output"); }
        set { Set("Output", value); }

    public void Execute_SayHelloCommand(object param)
        Output = "Hello, " + Input;

The latter is certainly better than the former, but my point is that there is a lot of ceremony and plumbing involved in order to get Silverlight applications wedged into the MVVM pattern.  Please don’t misunderstand me: MVVM is usually the best pattern for developing separated Silverlight applications.  I am only suggesting that there is a lot of ceremony.

In addition to my ViewModelSupport package, there are several other libraries out there that help you write implement MVVM in Silverlight including:

Presentation Model in Flex

In Flex, the binding system is very different than the way Silverlight does it.  Notifications are similar to INotifyPropertyChanged in Silverlight, but there is no interface specifically for property changes.  Instead, there is just an event that gets fired called “<property>Changed” where <property> is the name of the property that changed.  It is also simplified in that you can decorate your class or individual properties with [Bindable] and the Flex compiler writes all of your notification code for you.  As far as executing code in the Presentation Model, there is no ICommand like in Silverlight – the view simply calls into the Presentation Model directly. 

Lets say we have a simple application where the model is excluded because it is not relevant to what I am trying to show.  The behavior is simple: when the user presses a button, read the text in the input field and output “Hello <input>”.  A simple implementation of the view might look like this:

            var pm:PresentationModel = new PresentationModel();

<s:BorderContainer borderWeight="5" cornerRadius="5"
                   borderColor="black" minHeight="0" width="100%">
    <s:HGroup left="3" right="3" top="3" bottom="3">
        <s:TextInput width="100" text="@{pm.input}"/>
        <s:Button label="Say Hello" left="6" click="pm.sayHello()" />
        <s:Label left="6" verticalAlign="bottom" height="100%" text="{pm.output}">

The Presentation Model then looks like this:

public class PresentationModel
    public var input:String;
    public var output:String;

    public function sayHello():void {
        output = "Hello, " + input;

That’s it!  The [Bindable] flag tells the input and output properties to send inputChanged and outputChanged events automatically.  The sayHello function gets called directly from the view without the need to hook up a command.  It is really that easy to implement Presentation Models in Flex.

Much like the Silverlight side, there are frameworks that will help you along the way.  Because the binding system is as strong as it is in Flex (more details in a future post), you don’t need much to implement Presentation Models.  At a very minimum, though, I recommend using an Inversion of Control framework like flex-ioc, robotlegs or Swiz

Cross-Training in Silverlight & Flex — C#/CLR vs ActionScript3/AVM Part 1

December 17th, 2010

More Cross-Training in Silverlight & Flex In my previous post, I talked about the declarative side of Silverlight and Flex (XAML vs MXML).  In this post, I will talk about the imperative side Silverlight and Flex.  In other words, this is where developers write code that executes logic to modify state Read More...

Cross-Training in Silverlight and Flex – XAML vs MXML

November 8th, 2010

More Cross-Training in Silverlight and Flex Silverlight and Flex both include a declarative markup language for their UIs.  Microsoft calls the Silverlight specification Extensible Application Markup Language (XAML pronounced zammel).  Adobe calls the Flex specification MXML which is thought to have come from the original inventors: Macromedia extensible Markup Language Read More...

Cross-Training in Silverlight & Flex – The Future of RIAs

October 30th, 2010

More Cross-Training in Silverlight & Flex What a week for RIAs!  The first half of the week was consumed by the Adobe MAX conference where we got to see the future of Flex.  The second half of the week was consumed by the Microsoft PDC conference where many of us were hoping to hear about the future of Silverlight Read More...

Cross-Training in Silverlight & Flex – Platform Overview

October 26th, 2010

More Cross-Training in SIlverlight & Flex This is the second article in which I will compare the technical details between Silverlight and Flex. Before I jump into the nitty-gritty of the two, I thought I would give a general overview of the platforms that are Silverlight and Flex/Flash/Air. Understand these terms and the tools up front will make it much easier to cross-train on the two technologies Read More...

Cross-Training in Silverlight & Flex

October 24th, 2010

When I joined SRT Solutions a while back, one of the primary reasons for the move was to get exposed to new ideas and technologies. Although my first project at SRT didn’t stray much from my Silverlight expertise – an MVVM-driven WPF application – my second project is taking me in a slightly different direction Read More...

Adventures in Ruby MVVM – Wrapping it up

September 26th, 2010

More Adventures in MVVM Source code for the RubyMVVM playground on BitBucket It has been quite a while since I blogged.  Actually, I was just about to sit down to write this blog post about 7 weeks ago when my wife went into labor.  Soon afterwards, she gave birth to our second child -- a son named Eli Hecker Genisio Read More...

Adventures in Ruby MVVM – Bootstrapping Ruby

July 7th, 2010

More Adventures in MVVM In this post, I want to discuss how I am loading the ViewModels into the View.  When I write my Views, I like to use the tools I have available to me; Visual Studio and/or Expression Blend.  This means that I want a Visual Studio project and I want to be able to use these tools to create new views quickly Read More...

Adventures in Ruby MVVM – A ViewModel Base Class in Ruby

June 19th, 2010

More Adventures in MVVM In my last post, I talked about how to fire events from Ruby code such that .Net code can subscribe and receive them.  I showed a simple implementation of INotifyPropertyChanged; the interface that is essential to MVVM development in WPF and Silverlight. With that out of the way, I am moving forward to start building a simple ViewModel base class in Ruby that will let me declare notifiable properties with as little ceremony as possible Read More...

Adventures in Ruby MVVM – Firing Events from Ruby

June 14th, 2010

More Adventures in MVVM My Experiment: Can I move over to Ruby as my primary programming language when developing WPF and Silverlight applications?  I have been playing around with what it would mean to use Ruby to write my ViewModels, which would also make it easier to incorporate models using Ruby Read More...