“View Model” – the movie, cast your vote.

Star Wars Script by Richard Moross.

http://www.flickr.com/photos/richardmoross/3064808115/

No we’re not actually making a movie about View Model. If we were I am sure we’d get a low turn-out. :-) However it did get your attention.

What we are doing is some serious exploration into how we can help from a platform perspective folks that are implementing ViewModel (AKA Model-View-ViewModel  AKA Presentation Model)  in their Silverlight and WPF applications.

In the sense of a movie production, we’re in the script-writing phase. Here’s the general background.

Why is ViewModel important?

There have been many a post on the importance of ViewModel as a pattern and the benefits it brings. In that there is little disagreement that it benefits both developers and designers.

For developers it allows them to have clean separation of presentation logic from the UI rendering, thus making the app easier to maintain. It removes code from the code-behind that often makes the UI logic difficult to test.

For designers it provides a way for a designer to completely change the look of the UI in a tool such as Expression Blend, without breaking the application functionality. Furthermore it gives the designer freedoms beyond simple look and feel, to actually decide which data elements are exposed, as well as defining the interactions between the UI elements through commands and attached behaviors.

The debate over roles

Although the benefits of ViewModel are known, there’s quite a lot of debate both inside and outside Microsoft on the roles the developer and designer play in developing applications that use the pattern.  This runs the spectrum from the designer having complete control of every aspect of the UI,  to the development team having more of a tight handle on the UI components, and the designer being responsible for skinning. In either case there are tradeoffs.

What is important to you?

What is your experience with ViewModel today?

  1. Where does the platform help,? Where does it hinder?
  2. What can we do in the platform to make life easier?
  3. What role do developers / designers play in your application of ViewModel.

Like any movie, we need to touch on the right nerves in order to make it a box-office hit. We need your feedback so we can complete the script.

Thanks for your help

This entry was posted in silverlight, ViewModel, WPF. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://blog.excastle.com/ Joe White

    On INotifyPropertyChanged: I’m amazed that the compiler teams haven’t done anything about that yet. There’s already at least one third-party .NET language that addresses this pain (Delphi Prism, which has a “notify” keyword you can put on a property to make the class automatically implement INotifyPropertyChanged, and send notifications when the property is set). C# and VB could easily do the same.

    As for what could make ViewModel better: collection support. I haven’t seen a good story yet for having an ObservableCollection of objects down at the Model level, and wrapping each of those objects in a ViewModel automatically (while still keeping up with changes to the underlying collection). Maybe it’s there and I missed it, but this is my #1 pain point with MVVM.

  • http://www.scip.be Stefan Cruysberghs

    I really like the M-V-VM pattern but sometimes it makes everything really complicated. We are using Prism, RIA Services and we created several View and ViewModel base classes but still some issues are hard to solve. The issues that I have been struggling with are:
    - The ConverterParameter from a ValueConverter does not support binding.
    - DataForm Fields (SL3) have no DataContext. It is quite difficult to bind something in a DataForm to a ViewModel property once the CurrentItem of the DataForm has been set.
    The DataFormComboBox (SL3) is a terrible component which needs ValueConverters to work properly. But how to bind ValueConverters and lookup data from the ViewModel?
    - Where to put the DomainDataSource (RIA)? There should be some kind of PagedCollection class to use in ViewModels and to bind it with the DomainDataSource.
    - Commands from Prism do not work in ItemControls.
    - Silverlight should provide its one Command classes
    - The INotifyPropertyChanged technique should be simplified to avoid too much code.

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    @Chris

    Personally I am not a fan of the MVVM moniker, however ViewModel is actaully a lot clearer and succinct (to me) compared to PresentationModel which is ambiguous.

    As for the naming, there’s a bunch of reasons why the name was chosen, which do have validity. I used to get all bent out of shape about it, but I’ve moved on.

    When we were building Prism I used to call it the patty cake pattern (M-V-M-V-M-V-M-V). Needless to say, John wasn’t very happy about it :-)

    In general there is recognition that the patterns are the same thing though one is put in a specific context of a technology. Just a side note, I spoke with Martin Fowler about this and he didn’t seem to have much of an issue.

    Glenn

  • http://www.tavaresstudios.com Chris Tavares

    How about something really simple? Define exactly how MVVM is different from Presentation Model. If it’s not different, stop using an arbitrary term for something that’s already been around and well understood for decades.

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    @Paul agree that INPC type patterns have more usage than pure UI techincally, however I am at a loss to keep up with really valid scenarios for it. Meaning where one object needs to know about changes to another, and where that’s due to a UI binding scenario. Even if it is UI only, there is value in having a general notification stack that works across SL,WPF,ASP.NET, Win forms, etc.

    Generic base classes sounds good. I am meeting with the cider team tomorrow, and will echo these concerns.

    In terms of dynamic composition in XAML and embedding locators in XAML, this is actually something we’re working on in the MEF team. I posed a spike a while ago of MEF integration with XAML, that allows you to dynamically compose / set elements in XAML based on MEF contracts.

    For example you can do

    or

    Here’s the link to the spike if you want to check it out. I meant to blog on it, but oh well.

    http://cid-f8b2fd72406fb218.skydrive.live.com/self.aspx/blog/WPF%20Composition.zip

    Appreciate any feedback you have on this.

    On ISL in the framework, MEF actually has a very light abstraction under the hood called ExportProvider which allows it to talk to any source, for all intents and purposes it is ISL with some additional semantics that many container’s don’t yet support like metadata queries, but regardless it can still be used.

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    @Joe yep, pre-compilation is one path to validation. However, it can only validate that the bindings that are there are correct, not that bindings are missing. It could do warnings for VM properties that are not bound in the UI, but ViewModels are reused across different views where there may be a subset of props used, so the warnings would be invalid.

    On generating a class that derives from the base, that is exactly the dynamic proxy scenario I was describing.

  • http://www.paulstovell.com Paul Stovell

    My first thought would be to make INotifyPropertyChanged easier. Make PropertyChanged events part of the automatic properties system (e.g., if the class has an OnPropertyChanged(PropertyChangedEventArgs) method, have the setter call it). People need to understand that INPC is not a “UI” thing; it’s part of component model, and it simply says “an object represents state. Sometimes that state changes. Sometimes people are interested in that”. This shouldn’t require any form of AOP.

    Secondly, make Blend and Cider support generic base classes.* We’ve dreamed of a base View, but it breaks all designer support. If we could make this work it would make our views much easier to build. This is especially laughable considering PageFunction is part of the framework (and a very useful part).

    The designer tools also need better support for design-time only resources. Often resources are loaded dynamically (e.g., when you are designing views within a prism module, Blend won’t know about the app-level resources and usually breaks. Or, it encourages designers to add merged dictionary entries locally within the XAML, which has a huge runtime cost).

    Making IServiceLocator part of the framework would be nice, especially if you could bundle some markup expressions to work with it (e.g., ).

    Lastly, in XAML, why do MY classes need XML prefixes? I should be able to use my classes without prefixes. If there is an ambiguous reference imported, only then should I be forced into prefixes. That’s like the C# language forcing me to fully qualify the names of my own classes but not system types.

    * – Note that the designer doesn’t have to support classes where the generic type parameter isn’t know; in this case they are designing a View, so it’s perfectly known, but the designer still breaks.)

  • http://blogs.windowsclient.net/joeyw Joe

    @Glenn, agree on your point that XAML is effectively typeless and those silent binding errors can be a killer.
    Isn’t this a XAML/WPF stack issue though? Why not have a precompiler/validator that takes a XAML directive that associates a XAML file with a VM class, then validates all binding expressions?

    On the point about the framework/CLR support for INPC. For VM classes, I was trying to do this at runtime by dynamically generating the VM passthrough properties based on the underlying model. The dynamic class would be derived from your VM class that provides the additional VM properties.

  • http://updatecontrols.net Michael L Perry

    @Glenn

    Re: interface change breaks VM compile.
    Exactly. Make it a strong compile-time contract.

    Re: [Observable]
    That’s closer, but you should decorate the fields themselves, not the properties, and not the classes. See http://updatecontrols.net and the Independent sentry. It gives you an OnGet() and OnSet() to call whenever you access a field, and it figures out dependency through the View Model, through the properties. INPC is a thing of the past.

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    @Michael

    Interesting idea on the interface. So in Blend/Cider I would be able to add a member to the interface, which would ensure that the VM implements it, or it would not compile?

    The challenge I see there is that you might end up having VMs implement multiple interfaces as multiple views can bind to a VM each with a different set of data being displayed.

    My view would only want to “require” any VM it binds to, to offer up the members it needs, and your view the same.

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    @Joe like the idea of getting rid of all the INPC noise through proxies. I keep pushing on this internally, we really need a light mechanism baked into the framework to do this. Something that would let me do something like…

    [Observable]

    class Customer{}

    As far as the binding statements in XAML, personally (revealing my bias) I think having them in XAML is part of the problem as they are essentially “magic” strings that don’t get validated until runtime. I’ve personally spent countless hours in debugging due to broken bindings.

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    @Sean

    What is it that Prism doesn’t provide that you would want?

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    @Steele

    In terms of keeping the separation, I get you completely. Far beyond the tools, I think there needs to be an educational effort to teach people how to neatly apply separation of concerns, etc.

    I see what you mean abou can’t “see the results”, but can’t you use unit-tests on the VM to validate that the right result is returned? What is missing.

    One question I have for you about separation is around bindings. Who should define the binding between the View and the VM? And where should it live in an ideal world?

  • http://codebetter.com/members/gblock/default.aspx Glenn Block

    @Ryan

    Interesting. When we were building Prism in p&p, we had a similar experience. We hired a design firm to skin-up our UI. Once they gave us back the templates and such, we manually grafted them back into the main app.

    I talked about that in this post

    http://blogs.msdn.com/gblock/archive/2008/05/08/wpf-from-this-to-that-wow.aspx

    On the usage of pure DataTemplates I definitely see the value there. The one question I have for you though is how do you know the things are properly wired up in the templates? Do you use QA? Automated testing?

  • http://updatecontrols.net Michael L Perry

    Some of the pain points that I experience regarding WPF and MVVM are these:

    * Magic strings
    * INotifyPropertyChanged
    * Setting the initial DataContext

    Here are some ways that the framework could help alleviate some of that pain.

    First, don’t databind to named properties. Instead, databind to an interface. Write one interface in C#/VB, import it into Blend, and implement it with the View Model. Better yet, let it be a composite interface to support factoring. And make it possible to modify the interface from within either Blend or Visual Studio. This will give us compile-time validation of data binding, and it will give the tools more information about data types.

    Second, (shameless plug) use a dependency discovery algorithm like Update Controls rather than explicit change notification.

    Third, come up with a way for me to declaratively construct the View Model from app.xaml and make it the DataContext of the view. Perhaps make it more IoC friendly? I want NO code behind.

  • http://blogs.windowsclient.net/joeyw Joe

    Hi Glenn

    It seems to be all MVVM lately, which is great.
    MVVM serves many purposes. For one, it’s a far easier way of ‘converting’ the model to the basic binding constructs of the view – over the traditional value converters. It also removes the need for code-behind files, which didn’t really have a good architectural ‘home’. For others, I think MVVM acts as a model adapter. I know of some applications that use data-source dependent data models and use MVVM as an adapter to the data model required by their UI and application. In this way, for them MVVM is a RAD tool and a way to skip a domain driven conceptual model. Something I wouldn’t recommend, just an observation.

    As for developer/designer split. This probably applies to external applications – but remember LOB and RAD applications. The roles of a team are fluid, you cannot easily label people. Everybody’s skills and background are different. Remember the outcry when MS decided to split Visual Studio into editions?

    In my mind, the MVVM pattern should be the default way of using WPF/SL in the tools. Binding statements in the XAML should automatically create MVVM properties in the associated ViewModel (in much the same way as creating event handlers in the code-behind).

    I’ve also been looking at ways to create a dynamic ViewModel class that is acts as a shim onto the model class’s properties. This would avoid much of the needless property wrapping that some ViewModel authors embark on.

  • http://weblogs.asp.net/sfeldman Sean Feldman

    There are some recourses out there, some are good and some are less. What is missing, is a consolidate guideline for the best practises to utilize M-V-VM with WPF/Silverlight. Some samples are a mix, which can lead to misconceptions.
    IMO, having solid samples (similar to Prism) to cover most common scenarios (controls) is the way to go.
    Thank you for the “movie FXs” – waiting to see it ;)

  • http://steeleprice.net Steele Price

    Glenn:

    A Project Template to get started with MVVM would help, but more importantly, I think way too much time is being devoted to the complete separation between Designer and Developer. The Separation is good, but the tools (VS/Blend) don’t really address the more common scenario of a UI Developer who also does the design. This scenario needs VS and Blend to be able to help with intellisense, xaml parsing errors, data mocking (where does this switch? in the view model?) and Business Rules.

    Switching back and forth between these two tools is extremely painful and time comsuming. I can’t see my design in VS and I have no intellisense in Blend.

    Business Rules should be placed close to the UI, I think they should be in the ViewModel, because they are part of the presentation. But how can blend show the result of these being applied without running the Application.

    I should define “Business Rule”; this is something that I use to control what is displayed in the UI. It is not validation(this should be at the data level and bubble up to the ViewModel), but it may be Authorization choosing to show/hide Properties based on Roles. It also may be something that flags a record for highlighting, such as a Past Due Invoice.

    One big question has always been where and how to store these. In most cases they should be stored in a way that they can be changed dynamically without a recompile, persisted in a config file or a database.

    This presents a problem, how can we store expression trees. There are several debatable ways to accomplish this, but it’s not something talked about much, storing code and using reflection is one option, scripting is another. Neither of these are particularly optimal. A better story here would be really helpful especially when introducing stored variable logic.

  • http://wizardsofsmart.net/author/riles/ Ryan Riley

    Based on our fairly large LOB app, the ViewModel pattern has really helped us keep our screens organized and still testable. As it is, many of our ViewModels are still quite large, so leaving any of that on our Views would have left us out to dry re: tests.

    Oddly enough, we weren’t really able to integrate our designers as well as we had hoped. Expression adds so much excess that we had a developer trim the fat and just provided the designer the XAML as he needed it, rather than integrating him in with the rest of us. We found it better to keep him out of our source so that we could keep our XAML cleaner.

    I argued early that if we left the XAML to the designer once we did our initial layouts, we’d probably be happier and could still later do cleanup, but we found we were touching our XAML fairly frequently to keep up with bugs or enhancements from the client.

    As for making it easier, several of the devs on my team are agreed that we need to use DataTemplates for views in the future, as they just make the most sense from a ViewModel-first perspective. We don’t want a View-first model, and the application of DataTemplates to types is terrific–no hook-up code necessary.

    The only problem we have is trying to determine where to put the animation and state change logic. Sometimes that is more of a visual/design thing; other times that’s purely a business logic thing. Figuring out how to cleanly separate and apply those correctly is still an art form, or so it would seem. Also, trying to do something like the VSM in WPF is not trivial and generally has to be done on the View’s code behind. We would prefer to have that available on the ViewModel if possible.

    The other somewhat difficult element is the split on how to apply behaviors. We have used several Attached Properties for applying behavior, and those work well and can be easily traced back to the source. The question remains, though, as to whether that is really a ViewModel concern or a View concern. If a View concern, then these “attached behaviors” work well. If they are a ViewModel concern, then perhaps a ViewModel decorator is in order. As it stands, they work really well for us now; it’s more a matter of how to cleanly draw a dev/designer line.