The HoloLens Toolchain and XAML Grids

occlusion2occlusion

What tech stack will be used to develop applications for HoloLens, Microsoft’s innovative new augmented reality platform?

Keeping in mind that Alex Kipman is the visionary behind both HoloLens and the Kinect sensor, some clues can be gleaned from the current Kinect SDK. The Kinect SDK initially supported development in WPF and C++ with DirectX. Over time, however, and in line with Microsoft’s internal shift to be more open and embrace the tech stacks of non-Microsoft communities, the Kinect SDK has grown to include support for Unity3D, Cinder, OpenFrameworks, OpenCV and even MATLAB.

Legos vs Play-Doh

lego_vs_playdoh

This is a two-pronged approach to tooling that Microsoft luminary Rick Barraza has famously characterized as the distinction between building with legos and sculpting with play-doh.  Legos represent what Microsoft has traditionally been extremely good at: creating reusable components. Reusable components abstract the underlying technology layers so even beginning developers can accomplish difficult tasks without needing to understand the intricacies of networking, graphics cards, or memory management. As long as all you want to do is the 95% of tasks that Microsoft components support, legos may be all that you ever need. Microsoft has almost single-handedly created the modern enterprise software developer community based on component building, drag-and-drop IDEs, and copy /paste.

But what if you are not interested in building applications that look like everyone else’s? What if you want to do the 5% of things that reusable components do not allow you to do. This has typically been difficult. Not only does it require having a fine grain understanding of the underlying operating system but also a desire to hack around Microsoft’s safeguards. Because Microsoft had for so long embraced the component model of software development, it internally saw its role as one of safeguarding applications from attempts to follow any other model of software development. API classes are typically sealed to prevent extension and if one were to ask to have them unsealed, the inevitable reply was always “what would you use that for”?

Now lets consider a more playful software world in which it makes sense for classes to be unsealed by default so we can just start squishing them around in our hands to see what comes of it. This is software as exploration and in fact there is a whole community, frequently styled “creative coders”, who work in this way. The processing software programming platform created by Casey Reas and Ben Fry is the epitome of this movement. It was originally created as a better way to teach computer programming since it is built around drawing shapes rather than displaying text. From this simple and divergent starting point, all “hello world” applications are dramatically different.  Even more profound, however, it became clear that through simple loops and seed values, vastly different effects could be generated using only a few lines of code. Playing with processing feels like sculpting with play-doh. Other homologous tool chains were eventually created that shared processing’s emphasis on the visual rather than the textual: OpenFrameworks, Arduino, Cinder and Unity3D.

Which is a long-about way of saying that for premium experiences, these creative coding tool chains will likely be the tools of choice. If you want to get a jump start on HoloLens development, go learn these platforms:

 

HologramFramwork APIs

 hologramAPIs

I mentioned above that Microsoft has a two-pronged approach to tooling software developers. So far I have only mentioned the play-doh side. As we come closer to the Windows 10 release, however, there has been increased activity in the long dormant WPF platform team – enough to suggest that some sort of Holographic support might be released with a new version of WPF. WPF, after all, is Microsoft’s premier platform for component-based development. If the marketing ideal for HoloLens is to make as many HoloLens supported applications as possible straight out of the gate (as it should be), then an easy to use platform for building new HoloLens applications as well as porting old ones to the new paradigm is an obvious pre-requisite.

The image above is from enterprising colleagues who inspected the Windows 10 symbol packages to find out what kind of holographic support would be natively built into the new OS.  The initial impression is that low-hanging integration will be possible by using some sort of texture mapping model. For example, Silverlight provided a component called the VideoBrush that allowed any control that supported brushes to use a video rather than a solid or gradient texture as a background image. This included even complex 3D shapes or skewed geometries.

HoloLens Grids

occlusion4

To me, this suggests a grid-based programming model for quickly painting applications as textures onto valid surfaces identified by the HoloLens’s built-in depth sensors. The depth sensors will use computer vision algorithms to identify and tag surfaces in a room that can be used to project digital content. The user’s movements and any desirable digital-realistic skewing will be taken care of by the underlying holographic framework. For now, let’s assume that interactions will also be taken care of automatically and will follow a mouse-like hover/press idiom for convenience.

 simplegrid

XAML-based languages like WPF have a unique layout component called a Grid. Unlike tables in html, XAML grids define the layout and the content separately. The layout is specified in ColumnDefinitions and RowDefinitions – for instance one may specify a grid that is 3 X 3, or 2 X 1 (as above), and so on. Content is written out (or dragged) below the column and row definitions. Their placement in the layout is then defined by attaching positional directives on the content as shown below.

 grid2

In this code snippet, I haven’t defined a row so there is just one row by default. I have defined two columns which are a zero based array. Finally, I’ve specified on the green panel that I want it to be positioned in the first column by writing Grid.Column=”0” . The red panel, in turn, is placed in column 1, the second column in the series. The resulting WPF application is shown below:

grid3

In this case, the application is not particularly impressive. We can imagine the same code being written against the Holographic Framework with the following results, however:

occlusion3

And here is what the code for your first “Hello, World” application might look like:

holoworld

occlusion5

It is, I hope, not difficult to see how we can then go from a standard XAML Grid like the one above to a HoloLens-enabled Grid like the one below:

occlusion

At this point, given the dearth of information currently available (I’m dumpster diving through Windows 10 symbol packages, after all) this is obviously just a wild guess. I believe it is a plausible programming model, however, and would provide a royal road to quickly generate applications for Microsoft’s newest and brightest technology innovation.

The WPF Renaissance

mask

The ‘Mysterious Stranger’ is a stock device in literature.  Poe’s main character in The Masque of the Red Death is one instance of the theme.  Mark Twain left us an unfinished novel built around another.  An unexpected guest is central to one of the earliest works in English literature, Sir Gawain and the Green Knight.  In Plato’s late dialogues, Socrates is replaced by the more enigmatic Xenon or Stranger. The old testament is populated by mysterious guests who turn out to be angels.  The Venetian Carnival always potentially allowed commoners to mix with royalty since everyone was in disguise.  Middle Eastern literature is filled with Tufaylîs or ‘unexpected guests’ who would provide additional entertainment to any party should they be allowed over the threshold.  Medieval troubadours appear to have filled the same function in the West.

At the recent MIX 2011 keynotes in Las Vegas, amidst announcements about HTML5, IE9, ASP.NET MVC 3.x, Silverlight 5, Windows Phone Mango and the Kinect SDK, WPF made such an appearance.  It was never called out, as such, but as each Kinect demo was presented on stage, WPF aficionados were beaming because they recognized their old friend behind the Kinect mask.

Why WPF?  Because WPF is the natural workhorse for NUI development.  From Kinect hacks to multi-touch displays to Surface technology, it is again and again the technology of choice providing both native integration with low level touch messages on the host OS as well as a powerful programming idiom.  For many of us, it was the technology we learned to do MVVM on.  We get to use the full resources of the .NET Framework with it as well as the ease of development provided by Visual Studio and Blend.

And if we are at the beginning of a NUI renaissance, as my friend Corey Schuman suggests in his MIX presentation, it follows that we are also in the midst of a WPF Renaissance as, for now, NUI and WPF are closely bound together.

To add sauce to the goose, over the weekend Rob Relyea from the WPF team tweeted the following elliptical comment:

“Yesterday wpf team had champagne/sparkling cider at our all hands meeting. Reached significant milestone.”

As pleased as I was with the Kinect demos at MIX, this piece of messaging took me completely by surprise.  There are still WPF milestones?  The Microsoft Tufaylîs are indeed gifted at entertaining and delighting.

Silverlight 5, HTML5 and WPF

Last Thursday, Microsoft Evangelists Glen Gordon and Joe Healy held an all-day Silverlight firestarter in Atlanta.  It was a great event and will be travelling to Tampa, FL on 2/22 and Miami, FL on 2/24.

The real fun for me was what occurred afterwards.  Glen organized an Ask the Silverlight Experts panel in the backroom of a nearby sports bar.  After the ‘Bob Muglia Imbroglio’ – I wonder if that will ever catch on -  it was refreshing to hear people whose careers are deeply tied to the future of Silverlight actually speak candidly about it.  MVPs are typically cautious creatures, anxious not to speak out of turn, contrary to Microsoft strategy, or in violation of their NDAs with MS.  Following the Bob Muglia story, everyone is additionally anxious to not be the next person to torpedo Silverlight.

The panel was made up of Sergey Barskiy (Data MVP), Shawn Wildermuth (Data MVP, Silverlight Trainer), Jeremy Likness (Silverlight MVP, author of Sterling), Joel Ivory Johnson (WP7 Dev MVP) and Rob Schiefer (co-author of an upcoming WP7 book).  I was there representing the local Silverlight User Group which I run with Corey Schuman.   Jim Wooley (VB MVP) and Steve Porter (CAD MVP) were in the audience.

The first question asked, and the one that dominated the rest of the night, was to the effect of “What’s up with Silverlight and HTML5?”

I had originally planned to give a recap of all the arguments and theories but realized after attempting to do this for about an hour that I mostly just remember my own arguments and have, in my memory, distorted everyone else’s.

Then I came across this beautiful photo by Philip-Lorca diCorcia — who currently has an exhibit at the David Swirner gallery in New York City if you get a chance to visit – which summarizes everything that was said that night much better than I can.

lorca-dicorcia-wpf

In case it isn’t clear, the two dudes high-fiving each other on the right are Silverlight 5 and HTML5.

The Minority Report Demo You’ve been Waiting For

The Emerging Experiences Team at Razorfish has been working with NUI concepts on MS Surface for several years – and more recently on Windows Phone.  When the Kinect sensor became available we quickly grabbed the hardware and started exploring what could be done with it.  The above demo (coded and filmed by Steve Dawson) uses the Kinect and a physics engine to provide an experience that is Sorcerer’s Apprentice meets Minority Report.  Enjoy!

[Over the weekend we made it onto Endgadget and Gizmodo.]

Synchronizing Style Hierarchies with Control Hierarchies in WPF

WPF provides two ways to apply styles to control elements: by name and by type.  In the typical named style implementation, one declares both the name by which a style can be referenced as well as the control type to which it can be applied.  For instance, a style declaration for a ComboBox would look like this:

<Style x:Key="ComboBoxStyle" TargetType="ComboBox">
    ...
</Style>

When styles are applied in this way, the underlying WPF rendering mechanism understands type hierarchies.  Consequently, this style could also be written with a TargetType higher up in the Control type hierarchy and still work:

<Style x:Key="ComboBoxStyle" TargetType="Control">
   ...
</Style>

This is a handy feature when you want to build a custom control but want to preserve your styles.  For instance, the ComboBox control has no built-in ability to trigger commands.  If you want to use MVVM, however, this is quite a shortcoming.  You can overcome this problem by building a custom control based on the ComboBox type and implementing the ICommandSource interface to pick up the SelectionChanged event:

class CustomComboBox: ComboBox, ICommandSource
{
     ...
}

Since my CustomComboBox inherits from the WPF ComboBox, the named style I use with a TargetType of ComboBox will automatically be applied to it and the following XAML:

<Window x:Class="SampleWPFProject.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=System"
    xmlns:custom="clr-namespace:SampleWPFProject"
    Title="Window1" Height="300" Width="300">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="25"/>
        <RowDefinition Height="25"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0" Name="stackPanel1" Orientation="Horizontal">
        <TextBlock Margin="0,0,10,0" Width="60">Employees</TextBlock>
        <ComboBox x:Name="cbEmployees" SelectedIndex="0" Width="200" 
                  Style="{StaticResource ComboBoxStyle}">
            <ComboBoxItem>John Adams</ComboBoxItem>
            <ComboBoxItem>Ben Franklin</ComboBoxItem>
            <ComboBoxItem>Pat Henry</ComboBoxItem>
        </ComboBox>
    </StackPanel>
    <StackPanel Grid.Row="1" Name="stackPanel2" Orientation="Horizontal">
        <TextBlock Margin="0,0,10,0" Width="60">Tasks:</TextBlock>
        <custom:CustomComboBox x:Name="cbTasks" SelectedIndex="0" Width="200" 
                   Style="{StaticResource ComboBoxStyle}">
            <ComboBoxItem>Write Constitution</ComboBoxItem>
            <ComboBoxItem>Write Declaration</ComboBoxItem>
            <ComboBoxItem>Go for a ride</ComboBoxItem>
        </custom:CustomComboBox>
    </StackPanel>
</Grid>
</Window>

will fortuitously render itself like this, with the nice curvy boarders specified in my “ComboBoxStyle” style definition:

styleSample

But what if I want to apply my custom style arbitrarily to all ComboBoxes in my application?  This is where typed styles are very handy.

I can change the “key” element of the ComboBoxStyle to apply it generically to all ComboBoxes like this:

<Style x:Key="{x:Type ComboBox}" TargetType="ComboBox">
   ...
</Style>

Inside my XAML, I would simply remove the reference to the named style:

<ComboBox x:Name="cbEmployees" SelectedIndex="0" Width="200">
   ...
<custom:CustomComboBox x:Name="cbTasks" SelectedIndex="0" Width="200">

Unfortunately, the typed style does not understand that my CustomComboBox inherits from the ComboBox type, and the rendered window looks like this, reverting to the default ComboBox styling for my custom class:

 styleExample2

I could simply copy the entire original style and create a new one that specifies the CustomComboBox as the key, instead.  There is a shorter way, however.  I can take advantage of the BasedOn attribute of the style resource.  Rather than copy the entire style, I will create a new style based the original style and set the key to our custom type:

<Style x:Key="{x:Type ComboBox}" TargetType="ComboBox">
   ...
</Style>

<Style BasedOn="{StaticResource {x:Type ComboBox}}"  
       x:Key="{x:Type custom:CustomComboBox}" 
       TargetType="ComboBox"/>

Typically the BasedOn attribute is used to extend a base style with certain changes: for instance, off of a base style that sets  Button backgrounds to blue, one might want to create another that overrides the background color and sets it to orange.

This example shows that it can be used in a rather different way, however, to take a pre-existing typed style and apply it to a different type.  In this particular case, it is being used to align custom styles that are part of an inheritance hierarchy with custom controls that are part of a related type hierarchy.

Should it become necessary to extend the CustomComboBox control with a new custom control, in turn, one should be prepared to similarly extend the style hierarchy using the BasedOn attribute in order to maintain synchronization between one’s presentation and one’s functionality.

MVVM: UI design patterns in the wild

The Ascent of Man

Microsoft recently dropped an MVVM Visual Studio project template for the WPF Futures release of the WPF Toolkit on Codeplex.  In giving the history the MVVM UI design pattern, the documentation states that “[t]he origins of this pattern are obscure,” making it perhaps the first cryptozoological design pattern, discovered somewhere in the deep jungles of the Expression Blend development team.

MVVM is peculiar for a variety of reasons but the chief is that it does not originate on Martin Fowler’s Bliki as do the MVP and Presentation Model patterns.  Instead it is a found pattern.  Another peculiarity of the MVVM is that, unlike PM or MVP, it is not technology independent.  It is specifically targeted at XAML-based technologies, WPF in particular, and consequently tends to be described in concrete terms rather than abstract principles.

For me this is a strength of the MVVM pattern, since we don’t have to keep going back to a canonical document to find out if we are implementing the pattern correctly.  In fact, for a long time, if you implemented a UI design pattern in WPF, you could pretty much be assured that you were using a variant of the MVVM.  After all, who is going to correct you?

Without a canonical pattern document, however, we are very dependent on example code to find out how other people are doing it.  Currently my two favorites are Josh Smith’s WPF example http://msdn.microsoft.com/en-us/magazine/dd419663.aspx and Shawn Wildermuth’s Silverlight 2 example http://msdn.microsoft.com/en-us/magazine/dd458800.aspx .  It is especially interesting to contrast these two examples since many implementation details found in Mr. Smith’s example code are either impossible to implement in Mr. Wildermuth’s Silverlight example or simply not implemented.

Two key differences are the way Views are associated with ViewModels and the way the ViewModel encapsulates behavior.

In associating Views with ViewModels, it is important to remember that there are always top level Views and dependent Views as well as top level ModelViews and dependent ModelViews. 

On the UI layer, a WPF Window type serves as a container for various WPF UserControl types.  In the MVVM ontology, both are considered to be Views.  Because the structure of a ViewModel is closely associated with the structure of its View (ViewModel is, after all, intended to mean the Model of the View), this container-dependent object structure must be mirrored in the structure of the ViewModel.  If there is a top level View, then there must also be a top level ViewModel.  The top level ViewModel must, in turn, serve up additional objects and collections that correlate with the UserControl Views contained by the top level Window View.

Associating your ViewModel with the top level View

Gluing Views to ViewModels occurs differently for top level objects and dependent objects.  For top level objects, this binding is accomplished by setting the top level View’s DataContext property to its ViewModel.

Josh Smith’s code does this programmatically in the app class:

    MainWindow window = new MainWindow();

    var viewModel = new MainWindowViewModel();

    window.DataContext = viewModel;

    window.Show();

 

Shawn Wildermuth elegantly accomplishes this in XAML using Binding to set the DataContext of the View to a ViewModel loaded as an object resource:

 

Associating dependent ViewModels with their respective Views

We do not have to set the DataContext of any Views contained in the top level View. Once the top level DataContext is set, any elements on the container View should be aware of any public properties exposed by the top level ViewModel, since they will automatically inspect to visual tree in order to find a DataContext. 

Subsidiary Views are associated with properties on the top level ViewModel using DataTemplates and ContentControls.

In Josh Smith’s code, a  ContentControl is placed on the top level View in order to set an anchor for the association between the UserControl/View belonging to the top level View and the CollectionProperty/ViewModel belonging to the top level VM.  Here is a somewhat simplified version of what he does:

 

The HeaderedContentControl is combined with a TabControl are simply present to control how data is generally displayed.  The significant feature in this code is the binding on the Content property, which anchors the Workspaces property of our main ViewModel to this location.  In this case, the Workspaces property is an ObservableCollection of Workspace ViewModels:

        public ObservableCollection<WorkspaceViewModel> Workspaces

        {

            get

            {

                if (_workspaces == null)

                {

                    _workspaces = new ObservableCollection<WorkspaceViewModel>();

                    _workspaces.CollectionChanged += this.OnWorkspacesChanged;

                }

                return _workspaces;

            }

        }

Once the property is anchored, the appropriate View can be mapped to using a few WPF tricks:

 

In WPF DataTemplates normally have keys and a ContainerControl specifies the DataTemplate that will be applied to it based on those keys. By using the DataType property of a DataTemplate rather than setting a key, we invert this convention and let the DataTemplate determine what types of data it will be applied to.  In this case, we specify that this DataTemplate should be applied for any control with a Data Source of type WorkspaceViewModel.

You will also notice that instead of embedded Xaml inside the DataTemplate definition, we instruct the DataTemplate to apply a UserControl called AllCustomersView to WorkspaceViewModel.

There are some advantages to doing this.  First, Xaml embedded in the DataTemplate has no code-behind file whereas a UserControl does.  If you envision needing additional code to support your View, then this is a good route to go.  Second, UserControls are much easier to find in a Visual Studio solution than blocks of Xaml in a resource dictionary.  This makes UserControls a much better unit of work for organizing and maintaining code.  Finally (and this isn’t as trivial as it sounds) it gives us something we can call a “View” in the MVVM pattern.  WPF is so powerful, and allows us to do so many things in so many places, that it is useful to work with a View that can be treated as a fixed point around which we develop our applications. 

In Silverlight, sadly, DataTemplates can only be applied using named keys.  In Mr. Wildermuth’s code, the GameDetailsView UserControl is simply dropped into a Grid without the indirection of typed DataTemplates.  The Grid’s DataContext is then managed in code behind.

Another interesting feature of Mr. Wildermuth’s sample implementation is that he exposes raw Model objects.  While Mr. Smith’s implementation is careful to never expose Model objects, it could certainly be done without any obvious adverse affects.  For instance, the Workspaces property in Mr. Smith’s code exposes an ObservableCollection of WorkspaceViewModel objects.  It could just as well expose a collection of Customer objects, which is the type that WorkspaceViewModel encapsulates using containment.  This would affect our View code to the extent that we are using a keyless DataTemplate and must specify a type.  Had we chosen to specify a keyed template from the ContainerControl, however, then changes to the type of the collection would be transparent to our view.

The main advantage of wrapping our model objects in ViewModel objects is that we can coerce type conversions in the ViewModel rather than using TypeConverters in the binding in our XAML.  In general, a level of abstraction can always be useful.

The downside to using a ViewModel wrapper around our models is that in simple implementations we are simply duplicating each property of our Model object in the ViewModel.  This is a bit smelly.

How you implement MVVM will likely depend on your general coding tastes.  Some people like to encapsulate as much code as possible, while others prefer not to introduce abstractions unless they are actually required to accomplish a given task.  If you don’t use typed DataTemplates to apply your View to your ViewModel, then you have some flexibility in this regard.  The properties of your top level ViewModel can initially expose raw Model objects.  Should the need arise, you can later encapsulate your Model in a ViewModel without impacting the View.

Adding behavior through the Command infrastructure

Simply associating the View and the ViewModel in WPF takes care of data synchronization, assuming that your ViewModel implements INotifyPropertyChanged.  The other aspect of making the MVVM pattern work involves handling events on the View. 

In the MVP pattern, the Presenter typically handled events thrown by the View and routed them to the correct Presenter methods.

In MVVM binding is used on the View to associate events with actions on the ViewModel.

In Josh Smith’s code, this is accomplished by using DelegateCommands.  A DelegateCommand implements the ICommand interface and has an Execute method.  The Execute method, in turn, calls a delegate that has been associated with a specific DelegateCommand.  In Josh Smith’s code the DelegateCommand is called a RelayCommand.  There is an implementation of it provided in the Prism framework, as well as one in the MVVM Project Template included with WPF Futures.

To use DelegateCommands, you just need to first expose a property on your ViewModel of type ICommand.  Internal to the method a DelegateCommand instance is referenced that delegates to a private method on the ViewModel.  Here is a sample implementation from Josh Smith’s code:

    public ICommand SaveCommand

    {

        get

        {

            if (_saveCommand == null)

            {

                _saveCommand = new RelayCommand(

                    param => this.Save(),

                    param => this.CanSave

                    );

            }

            return _saveCommand;

        }

    }

 

The interesting part is how we bind to this property in our View.  In WPF controls typically have a default event that can be bound to a RoutedCommand by using the Command property.  The Command property, however, can also be bound to a property on the DataContext object that exposes an ICommand instance.

In our case, since the DataContext is already set to the ViewModel, we can simply take advantage of this to set the Command property of a Button to the SaveCommand property on our ViewModel:

There are a few shortcomings with this technique.  First, Silverlight 2 doesn’t support the Command property.  In Mr. Wildermuth’s example of MVVM, in fact, a button.clicked event is simply thrown and handled in code-behind;  the code-behind, in turn, calls a publically scoped method on the ViewModel.

The second shortcoming is that this only works if the default event handled by the Command is the one that you want.  If, in this case, we wanted to handle the right-clicked event, we would be out of luck.

There are several workarounds for this problem all involving creating attached properties to allow binding between control events and ViewModel commands.  John Grossman, who helped to promote the original MVVM pattern, has even dubbed it with its own pattern designation: the Attached Behavior Pattern, which works in WPF as well as Silverlight.

MVVM vs MVP

Technically, most of these binding techniques for data synchronization and behavior binding which are described as “MVVM” could be used in an MVP Supervising Controller implementation.  While traditionally one would hook up events between the View and the Presenter in the Presenter code, this seems a bit unnecessary since the binding works so well.  We aren’t changing responsibility between the Presenter and the View so much as we are simply finding a better way to facilitate this: instead of implementing an event specified in an IView interface, we are specifying the names of certain ICommand properties and allowing WPF to automagically hook it up for us.

As for data synchronization, while MVP Views typically know about model objects, there is no reason we couldn’t wrap model objects in containment objects just as, conversely, there is no reason we can’t expose raw model objects in MVVM rather than wrapped objects.

In the Prism sample implementations of the MVP pattern, moreover, the Presenter is often set as the View’s DataContext.  These similarities can make it difficult to distinguish between the two patterns in their wild habitat.  For instance, if you look at the source code for Scott Hanselman’s BabySmash application, you might be inclined, as I am, to identify it as an implementation of the MVVM pattern rather than the MVP pattern.

The key difference seems to be that in MVP the Presenter holds a reference to its correlate View, while in MVVM this is not the case.  In MVVM the ModelView/Presenter is unaware of the View that is being applied to it.  A typical Prism implementation of the MVP will look something like this:

    EmployeesPresenter presenter = this.container.Resolve<EmployeesPresenter>();

 

    IRegion mainRegion = this.regionManager.Regions[RegionNames.MainRegion];

    mainRegion.Add((UIElement)presenter.View);

In this case, dependency injection is used to pass a View object to the constructor of the Presenter.  The Presenter then sets its View property to this parameter value and ultimately returns it to the UI.

With the public View property on the Presenter, we are in the world of the MVP pattern.  Without it, we are probably in MVVM land.

A good way to differentiate patterns is to consider how and why they were developed in the first place.  The original concept behind the MVP pattern was to separate the View and the Presenter in such a way that the View had as little responsibility as possible. 

In the Passive View flavor of MVP, we weren’t even allowed to use the native binding provided in ASP.NET and WinForm development.  Instead, the Presenter was expected to populate each field on the View manually.

The Supervising Controller flavor of MVP, on the other hand, allowed us to provide a Model property on the View which the Presenter was responsible for populating.  The View itself, however, was able to bind its fields to this View.Model property itself.  This flavor of MVP gained popularity in large measure because it seemed silly not to use built in tools like binding for ideological reasons when it made development so much easier.

In WPF, we also have the ability to bind control events on the View to delegates on the ViewModel.  We could choose to wire these up manually if we wanted to, but again it seems strange to do this – and potentially introduce more errors – when WPF binding makes it unnecessary.

Set side by side, these three patterns resemble a child as it grows up.  In the Passive View pattern we are dealing with an infant and the Presenter is expected to feed and clean it.  I’ve tried letting infants feed themselves and it only leads to disaster.

In the Supervising Controller we allow the View to consume its own data, but we still take care of tying its shoes and any other details of hooking it up that are required.  It is still a toddler, after all.

In the MVVM, our baby has grown up.  Our View not only feeds itself but it also picks out its own food and ties its own shoes.  We don’t even have to keep an eye on it every hour of the day.  We can assume that it has a great degree of autonomy and can just come pull on our shirtsleeves if it runs into any problems.  It still needs to be aware of us, but we don’t need to be constantly aware of it.

For the most part this is where we want to be with regard to Views, but it comes at a cost.  When we place more code in our View we also make that code inaccessible for unit testing.  In WPF this doesn’t seem so bad because our code doesn’t show up in code-behind.  Instead it is marked up declaratively in Xaml.  And it’s mainly the code in code-behind that we care about testing, right? 

MVVM is probably for you if you are comfortable with either of the two following notions: 1) that Xaml isn’t really code, so it doesn’t need to be tested an 2) The whole point of declarative programming is that it behaves predictably, while the goal of unit testing is to capture unexpected behavior, so it doesn’t need to be tested.  If this causes you some discomfort, then MVVM is probably still for you if you feel that the convenience it provides outweighs any testability issues that might be raised – which is where I probably come down on the pattern.

Design Pattern Mutations

Like influenza, a design pattern can mutate over time.  This happens especially when it makes the species jump from one technology to another.

The Prism samples, in addition to the sample MVP implementations, also have an implementation of the MVVM that seems to combine aspects of both patterns.  In this implementation, the View keeps a reference to the PresentationModel, making it look like MVVM, while the PresentationModel also maintains a reference to the View much like a Supervising Controller.

The following code (modified slightly to simplify) can be found in the “Commanding” sample application for Prism:

    public OrdersEditorView View { get; private set; }

 

    public OrdersEditorPresentationModel(OrdersEditorView view)

    {

        View = view;

        view.Model = this;

    }

Best of both worlds?