AJ's blog

January 24, 2010

Silverlight Bits&Pieces: The First Steps with Visual State Manager

Filed under: .NET, .NET Framework, C#, Design Time, Silverlight, Software Development — ajdotnet @ 5:41 pm

Visual State Manager. Easy to understand in principle. But it takes some getting used to to be able to use it… .

There is a lot of information about VSM available, e.g. a quick introduction at silverlight.net, and when I first started to tackle VSM I read it all and then some (felt that way, anyway). Still, my first experiments with VSM failed miserably—and it did so because of a lack of understanding. Because the one main issue for me was that all the articles and screencasts explained what the VSM does and what great effects one (well, someone else) could achieve with it, yet all with the emphasis on ‚what‘ (and usually all at once), not on ‚how‘ (in small digestible chunks).

So, if you have looked into VSM and didn’t quite get it, but only just, then this post may be for you. First I‘m going to dive into some code, afterwards I’ll try to offer a few hints that should help you getting started with VSM.

The Crash Course

Controls have states (like normal, pressed, focused, for a button); states are represented by VSM as Visual States, organized in distinct State Groups. State Groups separate mutually independent Visual States (e.g. pressed state or mouse over are independent of the focus state). Silverlight allows to define these states in templates, along with State Transitions that define how the state change is to happen (e.g. instant change or some animation).

Silverlight also provides an attribute, namely TemplateVisualStateAttribute, to declare the supported Visual States and Groups on a control. Keep in mind however that this is merely for tool support and perhaps documentation. At runtime, the presence or absence of these attributes is of no consequence at all.

The Sample

OK, let’s see some code. I’ll build on the image button from my last post. It should support three different images, as well as a focused rectangle. (I’ll leave out the text though. I don’t need it and it would complicate matters for this post without gain.) The button class already defines the Visual States and Groups, I’ll stick with that.

First I extended the image button control class to support three dependency properties, namely NormalImage, HooverImage, and DisabledImage. (I could have added a ClickedImage, but I‘ll solve that otherwise.) To make a long story short, here is the custom class, defining the necessary dependency properties:

The button inherits the VSM attributes from its base class, thus I don’t have to reiterate them here.

Having done that I can already use these properties to set them in XAML:

Of course it still uses only the one image, I gave it last time. So, the next step is to extend the template with images, and other parts, to accommodate the Visual Styles. If I can live with XAML, I could do this using Visual Studio 2008. To do it in a design view I need Visual Studio 2010 or Blend.

In any case, this is conventional designing, it’s not yet time to look in blend at the “States” panel in Blend! And when it comes to this, VS2010 is also out of the game (at least in beta 2).

The resulting XAML looks somewhat like that:

Note that I used a Grid to stack the images on top of each other. Note also that the default settings for all parts are compliant with my „normal“ button state, i.e. the second and third image are invisible, so is the focus rectangle.

Now that my control contains all the primitives I need, it’s time to enter VSM. To prepare for that, I manually provided the State Groups and Visual States. This ensures that I get all states (Blend would only add the ones it manipulates, and since the normal state is going to be empty, it would always be missing), and in the order I prefer.

Now is the time to enter blend, select the button, then the current template, and have a look at the “States” pane.

Note that the “States” pane contains the State Groups with their respective Visual States. Blend gets this information from the TemplateVisualStateAttribute on the class, but also includes additional states and groups it finds in the template XAML. Additionally there is a “pseudo-state” named “Base”, which is simply the “state” in which the control is without putting it in a distinct state.

Now I went ahead, selected the state in question in Blend and changed the controls to match my design. Since I had the desired design figured out before I started the VSM – up to which properties to change for a transition – this was as simple as can be. For the mouse over state:

Note how Blend shows the design area with a red border and a “recording mode” sign. Every change to the template is now recorded as state change for the selected state, mouse over in this case. (You could switch recording off by clicking on the red dot in the upper left, and manipulate the properties ordinarily; yet selecting another state will switch it back on, so this is OK for some quick fixes, but too error prone for general editing.)
Note also that the “Objects” pane shows not only the controls, but marks those affected by the currently manipulated state with a red dot and puts the manipulated properties beneath. In case you accidentally manipulated the wrong property, you should remove this entry, rather than simply change it back, otherwise the (trivial) transition will remain in the XAML.

Just setting the visibility of two images results in some verbose and (at first sight) rather confusing XAML:

The disabled state looks similar. The click state is represented by the hover image which is moved slightly off center to achieve the click effect (“Properties” pane, “Transform”).

And here’s the resulting button in action, showing normal, hover, disabled, and clicked state:

Lessons Learned

What I just presented was a fast forward replay of employing the VSM. Using VSM minimalistic to the extreme actually, since I have left out quite a bit of VSM functionality, most notably transitions with animations. Still, I have applied some guidelines I learned to value when using VSM, that I’d like to point out.

So, here are some of the twists that made VSM useful to (rather by) me… (some learned the hard way).

💡 Hint 0 (The most general hint): States need careful planning.

If you don’t know yet what the control should look like in the various states, you should shy away from the “States” pane in Blend. Start with conventionally designing the control, It may even help to design a separate control template per state, and merge them only after the design has reached a stable state.

💡 Hint 1: Don’t look at existing controls.

It’s tempting to look at the existing templates, with Blend the XAML is only a mouse click away. Don’t. The button template has ~100 LOC, and I’ve seen others with more than 300 LOC. And what’s more, they are fully styled, meaning that they employed probably all the features, caring for sophisticated visual effects but not exactly for the poor developer trying to deduce the workings from looking at the XAML.

💡 Hint 2: Start simple.

Many samples quickly jump at animations used for transitions, easing functions, and slicing French Fries. For me one key to understanding VSM was to stick to the minimum at first. States. Transitions only as simple as possible. Period.

💡 Hint 3: VSM is not about creating states. It is about styling them.

My initial thinking was „I have a button with a normal image; in disabled mode I need to have a disabled image…“. This led to all kinds of mind twists, like „how do I create an image control during a state change?“ „Should I rather replace the image URL of the existing control, and how?“, and others. It was a crucial part of understanding when I realized that I do not have a button with one image in one state and another image in another state. What I have is a button with three images in all states, as presented above. The difference between the states is merely which of these images is visible and which is not.

💡 Hint 4: When designing a new control, avoid the VSM “States” pane for quite some time.

There is one pitfall I managed to hit several times in the beginning. I started Blend, selected the particular state I‘m interested in, and tried to design my control for that state. This is futile, because Blend does not actually design the control (as in setting property values), rather it designs the transitions to these values. (You could switch off recoding mode, but Blend really insists on switching it on again and again and again.)

Therefore I generally design my control „conventionally“. I.e. I place the normal image in a grid and style it; then I make it invisible (kind of a manual state change) and do the same with the next image; and so forth for all states. Only when I‘m done with this I allow myself to even look at the VSM support in Blend.

💡 Hint 5: The visual state for the normal state is always there. And always empty.

Worse, you’ll have to include it manually in XAML, since Blend doesn’t put it there… 😦

„Normal state“ is the default state of the state group. Each state group has one; it doesn’t have be be named „normal“, but it has to exist. This is the state in which the control is by default, after initially displaying the control, and before VSM has even touched it. The one that is denoted as “Base” in the “States” pane.

The „normal“ state has to be declared, because otherwise the control will not be drawn correctly after it has been in a different state, say normal –> hover –> normal. And it has to be empty because otherwise the control would show up in an undefined state, at least according to VSM, which can never again be reached, once the control was in a different state. This would lead to all kinds of inconsistencies.

Lemma: All controls in the template initially have property values compliant with the normal state. In the image button example: The normal image is visible, the other images invisible.

💡 Hint 6: VSM is not about designing states. It’s about designing differences between the state in question and the normal state.

Suppose I have the control designed the „conventional“ way with the looks of the normal state; I also have yet invisible controls for the other states. Now is the time to enter Blend and the “State” pane. Choose the state in question, e.g. mouse over, and manipulate exactly those properties that constitute the difference between normal state and mouse over state. I.e. set the normal image to invisible and the hover image to visible. Blend will record the respective transitions.

It’s always this difference, always normal state vs. the state in question. Only if you achieved the first belt in using VSM and signed the no-liability warrant should you go ahead and attack transitions between specific states, for complexity will explode.

💡 Hint 7: State groups are mutually independent. And the same is mandatory for the state differences.

Never let different state groups manipulate the same properties. For example the button addresses common states and focus states independently. It would not work to implement the focused state by setting the hover image visible, as this would collide with the mouse over state and eventually result in undefined behavior. The focused state could show a focus rectangle. Or it could actually even manipulate the hover image, as long as it is not the visibility property used by the mouse over. (Whether that makes is a different question, though.)

💡 Hint 8: Visual states are not put in stone.

Controls usually have visual states defined via attributes. However this is just some information, used by some tools (such as Blend), but of no consequence otherwise. VisualStateManager.GoToState is what triggers a transition, and it may or may not be called from the control itself. The visual states and groups defined in the template are merely backing information used at runtime. Should the need arise, I could define a new state group, say „Age“, with two visual states „YoungAge“ and „OldAge“ in XAML. Then I could go ahead and call the VSM from the code behind file of my page class to change the state. And after 5 minutes of inactivity my button could grow a beard.


So far the hints. But what about more complex demands? I have barely touched the eye catching features at all.

In my opinion, what I just presented will cover the first steps and provide a sound understanding of the core VSM principles. Once this level of understanding VSM is mastered, one can go ahead and explore other areas.

And there certainly are “other areas”. I already mentioned state specific transitions; animated transitions are another topic. If you need an example of what’s possible have a look at this online sample. This is VSM in action, admittedly complemented with some code, but surprisingly little. (You can dig into it starting Blend and opening the sample project „ColorSwatchSL“.)

Some other useful links:

And from now on it’s no longer a lack of understanding that keeps me from doing things. It’s my incompetence as designer… 😉

That’s all for now folks,

kick it on DotNetKicks.com

January 17, 2010

Silverlight Bits&Pieces: Derived Custom Controls

Filed under: .NET, C#, Design Time, Silverlight, Software Development — ajdotnet @ 3:06 pm

OK, let’s put the last findings to good use and create a derived control that carries its own default template. This post is again about some fairly basic stuff, but it is the logical next step.

My use case: I wanted/needed a simple image button, one that simply takes the image as a property, rather than having to manipulate the content for every button anew. So what do I need?

  1. A derived class.
  2. A dependency property for the image URL.
  3. A new default template.

Deriving a SL control is just a matter of clicking add/new item in the solution explorer, and choosing „Silverlight Templated Control“. This will actually create 2 things (and address the default template requirement as well…):

  1. A class derived form Control, placed in a .cs file in the folder I used to create the new item.
  2. A XAML file named Themes/Generic.xaml is created (or extended if it already exists) and contains a style and template for the new control.

Now, the implied behavior is that a custom control sets its DefaultStyleKey property to a type (usually its own). At runtime SL will determine the default style of a control by using this type’s assembly to read the Themes/Generic.xaml content and pick the style that has the type as target type.

Note how the style in Themes/Generic.xaml uses an XML namespace to map the class name to a C# namespace:

Note: One consequence of this is that all styles of all custom controls in an assembly will end up in the same generic.xaml file. This is usually not an issue, even if implementation and style/template reside in relatively remote files. However, if the assembly grows to accommodate a bigger number of controls, it might make sense to put the control specific resources into separate .xaml files right beside the implementation. Loading the template from a .xaml resource is no big deal, all you need is GetManifestResourceStream and XamlReader.Load, in more detail here.

The next step is to change the base class — I want to extend the Button, not write it completely anew — and to provide the dependency property for the image. Having a peek at the Source property of the Image control tells me that ImageSource is the adequate type.

Now, let’s customize the appearance. Unfortunately Blend cannot deduce the dependency between the control an the style in Themes/Generic.xaml. Therefore its easier to create an instance of the ImageButton, assign a temporary style with template in blend, placed it into the same page’s XAML:

and the respective button:

Of course I need to have the respective image…

I can now use Blend to work on the template (assigned within the style):

This will change to editing context to the template rather than the control:

I changed it to include the image, placed it beside the text. (Actually, placed beside what I choose to have in the content property, using a content presenter.)

Now I want the image control to show what I have in the NormalImage property I just wrote. Blend is aware of the type of my class, so I can bind the Image.Source property using a template binding to the property of my class.

and clicking it:

The temporary style with template finally looks like this:

Template bindings can be used to bind against existing properties (of appropriate type), as well as any new property I choose to provide. Actually for a complete implementation I would probably have to map alignments, and other properties accordingly to parts of my template, to provide full customizability for my control.

Now that I’m done designing my button, I can save it, copy the resulting template into the default style for my control in Themes/Generic.xaml, recompile – and then just use it:

Just an image, no text; and at runtime:


Alright, that’s the basics of a custom control. Essentially what I’ve done is

  • replacing the default template with one that includes an image
  • providing a dependency property for the image, actually nothing more than a mirror of the respective property of the image in my template.

This is all very boilerplate on one hand, yet extremely flexible at the same time.

Now, the image of the button does not „feel“ very buttonish, i.e. it does not reflect mouse over, disabled state, or clicked state. This is the domain of VSM. Next post…

That’s all for now folks,

kick it on DotNetKicks.com

January 10, 2010

Silverlight Bits&Pieces: Controls Basics

Filed under: .NET, .NET Framework, Silverlight — ajdotnet @ 5:26 pm

Silverlight is all about controls, and I have yet barely touched them. It’s about time to change this.

And since controls are such an ingrained feature of SL, I can safely refer to others for the bread-and-butter explanations and focus on the key points afterwards. (Still, is post is going to be about fairly basic stuff.)

The basics…

Done 😉

OK, this would be a short post, if that where indeed it.

Actually this is how I started. Using controls the way I did in WinForms or ASP.NET, setting properties, layouting, styling. It is all so common and natural, I didn’t spend much thought on controls per se at first.

However, treating SL controls like WinForms controls doesn’t do them credit and neglects quite a bit of the potential. Actually, in my opinion, the SL control system is one step ahead of all previous systems.

The Key Point About SL Controls…

… is this: Silverlight clearly and cleanly distinguishes and separates behavior (control type), shape (control template), and style (control style).

And the glue holding this triumvirate together is the properties, more accurately dependency properties. The following image is an attempt to describe this relationship:

  • Controls define their properties, and only the properties defined in a control are accessible for manipulation via styles or to be referenced by templates.
  • Templates make up the shape of the control, by assembling Parts into a new compound representation.
  • And styles set property values that affect either the behavior or are referenced by the template to affect the appearance or content of a Part.

Add the fact that properties may be subject to databinding and you get a very concise system.

In More Detail…


SL controls come as classes (surprise!), but their job is only to define behavior (unlike WinForms or WebForms controls that also do the rendering). E.g. a button control essentially does three things:

  • It defines behavior. I.e. it reacts on mouse over and mouse click to render a hover effect or trigger the click event.
  • It defines (dependency) properties. The properties offer a way of controlling the behavior and appearance – if the control code or the template chose to refer to them.
  • It triggers the rendering process, deferring it to the template(s). Usually controls bring their own default template within the resources, many let the template be replaced either partly (usually by setting a Content property), or completely by setting some Template property.


Styles are essentially a way to set a couple of properties of a control. Period.

To be more elaborate, Styles don’t care whether those values actually style the control in the sense of designing it. For example I can set the selection mode of a data grid, which affects the behavior rather than the design. Styles can set virtually any property of any control, including the one I haven’t even written yet. Styles are also not restricted to certain (and in these cases typically simple) types; leveraging the power of XAML, styles can assign virtually any value of any type.

Lemma: Styles can only manipulate properties. Meaning if I need a button with an image I cannot simply set the image via a style, because the standard button control simply does not have a respective property. I need to derive a control and define a respective dependency property.

Since those properties are class specific, styles are consequently type specific (contrary to CSS), and have to unequivocally state that type. Hence one cannot define a style (say setting font type and size) and apply it to a textbox as well as to a link control. To one who is used to CSS this may come as a restriction.


Basically a template is the XAML representation of the Parts that together constitute the visual appearance of a control. This can be a mixture of primitives, but it could also incorporate other controls. Also there is some degree of “behavior” in the sense that this may include animations, visual state manager information, and other dynamic content. Depending on the control, a template can be partly set via some content property or completely via some template property. Some controls may offer more than one template, e.g. for header and cells in a data grid. Templates can refer to properties, by way of TemplateBinding, and those properties can afterwards be customized via styles.

Depending on the control (which carries the logic to “activate” them), templates can offer a wide spectrum of extensibility. As an example consider the following textbox, using an alternate template:

This template adds a small glyph to the textbox and sets its tooltip to the textbox content. And this is the result:

This is not bullet proof (changing the text won’t update the tooltip), but it should give a first hint on the potential of customization via templates.

Add visual state manager and states for mouse, selection, validation errors, put animations on top, and you get an unprecedented customizability of even the most basic controls. The down side is the unprecedented complexity, for example the template for the date picker control (extracted via blend) has about 150 LOC, and I have seen other with over 300 LOC.   

Some Conventions…

SL controls don’t adhere to some global style, i.e. it is not possible to somehow state that every textbox should use a certain font within a given application (this is one of the new SL4 features, though). To make my default style assignments easier I like to have standard styles named after class (i.e. "Textbox” – not “DefaultTextbox” or “TextboxStyle”, or some other convention). One could replace the standard classes with derived classes or use some other generic mechanism, yet so far Blend and manual assignment worked fine for me.

Regarding templates, I generally don’t set the Template property within the page XAML. Rather I like to assign the template indirectly via a style. This way I won’t have to think about setting both properties, style and template, and worry about dependencies. Applied to the example above:

And the respective style which also sets the property:


If styles and templates are that powerful one could assume that the need to deriving controls was less prevalent. Matter of fact I do derive controls as often as before, only the reasons have changed: Mostly I derive controls to define properties that I need within custom templates and styles.

And I thought this might be a shorter post…. Anyway, the next post will lay out some additional basic stuff before I’m going to tackle derived controls and VSM.

That’s all for now folks,

kick it on DotNetKicks.com

January 1, 2010

MVVM needs (re)definition

Filed under: .NET, Silverlight, Software Architecture — ajdotnet @ 3:41 pm

So, the last two posts made the point of showing that MVVM has a rather fragile theoretical foundation. Either that, or it is constantly misapplied.

Matter of fact, there are two incarnations of MVVM. In order to distinguish them, let’s call them MVVM/PM and MVVM/SC respectively.

As a quick recap: The relevant difference between the Presentation Model pattern and the Supervising Controller Patter (and the MVVM derivates respectively) is whether the View gets access to the Model’s data model or not. The patterns are very similar, but they differ in this one important aspect.

See my preparatory posts for details. Another descriptions of the two patterns with the same distinction can be found in the Composite Application Guidance for WPF and Silverlight documentation.

One could argue that this difference is superficial, even that Supervising Controller is actually a special case of Presentation Model (if you promote Fowlers exception for read-only data to the be the norm). In fact, when I discussed this whole topic with other people, about half of them fell into the camp that didn’t care at all and rather took the pragmatic approach, like “Who cares, I use MVVM the way it suites me, no matter what some useless theoretician thinks I should be doing.”. But even they didn’t argue the fact that there actually is something wrong with the theory.

The Problem with the Theory…

Theoretical musings aside – and presuming we agree that there are two different MVVM patterns – why is that a problem?

Well, I see several problems:

First, if someone tells you, he is using MVVM, he communicates something.

This is the most important achievement of the GoF with their groundbreaking work on patterns: Simply by providing a catalogue of abstract relationships of software artifacts and naming them, they established a vocabulary. This vocabulary is a means of communication, a way of talking about abstract concepts. What this has done to foster knowledge reuse, software quality, and documentation aspects can hardly be underestimated.

However, having a term with contradictory meanings will destroy that means perhaps more severely than not having a respective term in the first place.

Second, having a solid theoretical foundation, a clear concept, leads to a better understanding in general.

It is the concept that guides me if I have to face a situation that is not really addressed by the current implementation. And implementation has to follow the concept, not vice versa.

If I know what the theoretical foundation is, it can help me answering certain questions. Or it can tell me clearly that a particular topic isn’t covered by this pattern, hence I will know that I’ll have to look elsewhere. Without a solid foundation I won’t get any guidance, I would have to solve every problem on my own, and I would be in danger of violating principles that I’m not even aware of.

Third, on the practical side, we need to clarify the theoretical foundation to tackle the actual issue: Neither approach does actually help by itself.

As an example take validation. Validation in SL3 works by putting validation code into property setters or applying validation attributes to them. However, neither option is feasible with the code generated service proxy classes. Alternative approaches I found, like attaching code to the property changed event, are not very satisfying to say the least. Other demands include thoughts about generic caching or offline support.

  • MVVM/PM solves this issue quite easily within the PM. But having to replicate the data model leads to a maintenance nightmare. And (at least in the Silverlight area) it’s hardly employed, anyway.
  • MVVM/SC (the usually employed pattern because it works very well with the tooling) simply stops short of answering questions regarding validation.

Actually it has been the issue of validation and thoughts about caching and offline support that triggered all these thoughts and sent me back to the drawing board, investigating the concept, and trying to find out what the theory tells me. Well, I found two different MVVMs…


So, I did wreck MVVM, didn’t I? Sorry. Couldn’t be helped.

In my opinion, the only solution for this mess is a redefinition of the term MVVM. This in inevitable, I’m just not sure how this will happen. The concept could evolve and form a better theoretical foundation. But then, people could also continue to neglect the theory and come up with “pragmatic solutions” – meaning that MVVM becomes a fancy umbrella term for anything that looks remotely like PM or SC.

Personally, I would certainly prefer a sound theoretical foundation, probably one that emancipates MVVM from its two parents. Actually I would go where the tooling goes (see Dan’s post), because this is what people will do in the long run, and with good reason. Thus I would start with MVVM/SC as MVVM. From there I would either extend MVVM or complement it with other patterns to address validation, caching, synchronization for offline applications, whatever.

Yes, this would imply redefining MVVM to stem from SC rather than PM, and to accept VM as misnomer for the sake of continuity. And additional concepts to fill the gaps, that may yet have to evolve. However, this is what people think they are doing, anyway. It’s simpler to adjust the theory than people’s perceptions.

One important note: I deliberately ignored WPF! While MVVM started there and was reused with SL, it may be the case that the special demands of an SL application may cause MVVM to evolve differently for the two technologies. (It may not. Still, I’d like to keep that door open.)

So far my criticism. I’m aware that I just redefined (or rather dumped?) a well-established term, and I’m not someone like Fowler who does that on a daily basis. So I would be interested in opinions. Just tell me if I went over the top.

That’s all for now folks,

kick it on DotNetKicks.com

Excursus: Supervising Controller Pattern

Filed under: .NET, Silverlight, Software Architecture — ajdotnet @ 3:35 pm

Note: This is the second preparation post for an upcoming MVVM related post (which got definitely too long)….

The Supervising Controller pattern (previously known as Supervising Presenter pattern) goes back to Fowler ([Fowler-SC]). What makes it relevant for Silverlight development is that it is the usually employed pattern.

Similarly to the Presentation Model (PM) pattern, the Supervising Controller pattern essentially contains three parts: View, Model, and Supervising Controller (SC). The SC pattern provides “the ability to easily map between the view and model, often using some kind of Data Binding”. The mediator between the View and the Model is the SC: “A Supervising Controller has two primary responsibilities: input response and partial view/model synchronization.” ([Fowler-SC])

While the SC pattern is very similar to the PM pattern, the relationship and responsibilities of the parts are somewhat different. For an SL application it looks like this:


Compared with the PM pattern, the difference is seemingly minor: The SC lacks the responsibility to establish a data model, rather there is an additional arrow from View to Model. However, this is actually (at least in comparison to the PM pattern) the defining characteristic of the SC pattern: The View interacts directly with the Model (contrary to the PM pattern). The SC acts only as a mediator, once the connection between View and Model is established, the SC is no longer involved.

The SC has the following responsibilities (leaving aside view entities, as they constitute only a minor part of the data model):

  • Handling the controller logic part
  • Talking to the service

Obviously the SC as less responsibilities than the Presentation Model, resulting in less complexity, and better separation of concern. On the other hand it is also less flexible and thus less applicable in complex cases.

The Relation to MVVM

Matter if fact, this is the way MVVM for Silverlight is usually presented: If you find a more recent description of Silverlight with MVVM (which is curiously not that easy), it is probably similar to my own introduction. Dan Wahlin has recently written about the topic, focusing on SL, and it’s probably the most concise introduction to MVVM with SL I’ve found so far. And again, his code snippets and text descriptions clearly follow the SC pattern. (Curiously his images follow the PM pattern, but since he never names it and takes a rather pragmatic approach anyway, I’ll leave it at that. 😉 )

Notwithstanding the verdict: From a purely formalistic point of view, this is simply wrong! If MVVM is defined as a derivate of the PM pattern (as it was originally introduced), it cannot follow the SC patter at the same time. Both patterns follow contradictory approaches regarding the data model and the resulting ViewModel responsibilities. Actually it is even worse: Since it is not even a responsibility of the SC to define a data model in the first place, the term ViewModel is grossly misleading.

However, given that the Model for SL applications is usually code generated and supports everything that is needed for databinding, the beauty of this approach is its ease of use. At first. (In other words, stay tuned…)

That’s all for now folks,

Excursus: Presentation Model Pattern

Filed under: .NET, Silverlight, Software Architecture — ajdotnet @ 3:24 pm

Note: This post is a preparation post for an upcoming MVVM related post (which got definitely too long)….

The Presentation Model pattern goes back to Fowler ([Fowler-PM]). What makes it relevant for Silverlight development is that it is often cited as the underlying pattern for the Model-View-ViewModel pattern.

Essentially the Presentation Model pattern contains View, Presentation Model (PM) and Model. And it actually comes in two flavors: “An important implementation detail of Presentation Model is whether the View should reference the Presentation Model or the Presentation Model should reference the View. Both implementations provide pros and cons.” ([Fowler-PM])

Interesting (but irrelevant for this post): “A Presentation Model that references a view generally maintains the synchronization code in the Presentation Model. […] The views implement interfaces allowing for easy stubbing when testing the Presentation Model.” 
This leads straight to the Passive View incarnation of the MVP pattern, also supported by the WCSF. The other incarnation of MVP is the Supervising Controller (which will be the topic of another post). The pattern ecosystem certainly has some relations…

Now, the View referencing the PM (Fowler explicitly mentions databinding) leads to MVVM/PM. Given Fowlers rejection of DTO’s its fair to assume that he had a Model constituted as BO’s in mind, with the BO’s talking directly to the next layer. However, I’ll skip that and stay with DTO’s as Model. Personal opinions aside, the common case with SL applications is using code generated service proxies, especially the service contract, as Model.

Hence the relationship of the participants in an SL application would look like this:


Fowler states it himself: “The essence of a Presentation Model is of a fully self-contained class that represents all the data and behavior of the UI window,” ([Fowler-PM]), meaning that the PM constitutes its own data model, and the View does not get access to the Model.

This is actually the defining characteristic of the PM pattern: The PM provides – constitutes – is – a data model, separate from the Model; the View is shielded away from the Model and doesn’t get access to it or its types. (It consequently follows that the pattern requires a duplication of the data model – hence the name Presentation Model – that is largely readily available with the Model.)

Thus the PM has several responsibilities:

  • Defining its own data model
  • Mapping the data between the two data models (using wrappers or other means)
  • Handling the controller logic part
  • Talking to the service (with BO’s rather than DTO’s, it would be their job to do this).

The Relation to MVVM

John Gossman’s post “Introduction to Model/View/ViewModel pattern for building WPF apps” (written 2005!) is generally referred to as the “introducing post”, bringing MVVM into existence. If only somewhat between the lines, but he introduces and defines MVVM as derivate of the PM pattern (without actually naming it); Wikipedia declares MVVM “as a specialization of the PresentationModel design pattern”, and the often quoted MSDN article “WPF Apps With The Model-View-ViewModel Design Pattern” follows the same principles.

Hence MVVM also suffers from the need to replicate the data model. John Gossman states that “only a small subset of application UI can be data bound directly to the Model“, and thus it is feasible to pay for this effort and the implications. However, if you don’t agree with this assessment (like me, for one), you could argue that this leads to meaningless replication.

Note: Fowler actually acknowledges that and states: “One area where data binding can work very well is with read-only data, […] The presentation model in this case reveals its internal data set as a property. This allows the form to data bind directly to the cells in the data set.”

However, this is a shortcut (kind of a degeneration) for read-only cases, in order to leverage data binding capabilities.

And by the way: If this is not exactly what you do if you say “I do Silverlight with MVVM…”, welcome to the club. That’s what started this post in the first place. More on this in the next posts…

That’s all for now folks,

Blog at WordPress.com.