Alex Rivera | Logout

What are the pros and cons of View-first vs. ViewModel-first in the MVVM pattern

Asked 2010-09-21T17:57:56.010
52

I'm giving a presentation on using MVVM in real world applications and I'm including a section on the religious wars design decisions involved when using MVVM as a pattern in your application. In an MVVM application there are two main ways (that I know of) to instantiate a new View/ViewModel pair:

  1. View-First in which you create a view and it creates its own ViewModel and sets it to its DataContext.
  2. ViewModel-First in which you create new view models and create new views in response to changes in ViewModel properties, usually with ItemsControls and/or DataTemplates.

In your experience what are the pros and cons of each method? What do they enable and what problems do you run into with each?

Result Summary


  • View First - Pros
    • Easy to track which ViewModel is used by a View
  • View First - Cons
    • Doesn't allow a single View to be easily used with multiple ViewModels
    • Requires extra events to handle communication between Views and ViewModels
  • ViewModel First - Pros
    • Allows more complete testing of logic to open new Views and ViewModels
    • Tends to be DRYer as applications get larger
    • View and ViewModel are more independent and can be worked on separately more easily
  • ViewModel First - Cons
    • More difficult to set up in Silverlight without DataTemplateSelector and typed DataTemplates.
Edit
Report

2 Answers

21

Given the Data Templating feature in WPF, I feel ViewModel-First is the way WPF was intended to be used.

I'll clarify that statement: Data Templating allows you to never instantiate views from your ViewModel. If done correctly, your Views and ViewModels could be kept in seperate projects that DO NOT reference each other. Furthermore, the ViewModel project should not even reference any PresentationFramework assemblies, making your ViewModels consumable by any conceivable user.

answered 2012-10-18T08:56:22.073
0

I use a View-first (sort-of) approach. I define the View in collaboration with my client with a dummy viewmodel with test data. When we are satisfied, I proceed to extract an interface from the 'dummy' and implement the real ViewModel. I've found this approach most appealing for the following reasons:

  • It's fast as prototyping is in-expensive time-wise and I often get it right (ish) in the fourth or fifth try.
  • ViewModels tend to be easy (easier) to implement when I have an interface to adhere to.

I work in WPF, but I'd think it wouldn't be too different in SL. Also, I never spend time on testing views which may attribute to my choice of approach.

answered 2010-09-21T18:10:13.720

Your Answer