M-V-VM

Last Updated: 2-7-2010

WPF & Silverlight Line of Business UI Design Pattern Home Page

This page is a work in progress and will be updated each time a new article is added.  My goal is to provide an introduction, several simple examples and progress to a series of WPF LOB scenarios where M-V-VM is used.  Scenarios like, dialog box, simple form, master – detail, complex master detail with several embedded ViewModels, etc.

I use the common terms Model-View-ViewModel, M-V-VM and MVVM so that Internet surfers can easily locate this material using those names.  I like to think that this material extends past the boundaries of the M-V-VM pattern and provides good guidance for authoring WPF LOB applications.  Once this series is complete, I will go back and finish the WPF Business Application Series and use this material as a foundation to build some cool applications for that series.

M-V-VM is a guideline, a pattern that developers can elect to use when authoring WPF applications.  I like this pattern because it makes unit testing your application very simple.  In fact, John Gossman’s litmus test for M-V-VM is that the application can be run without the UI.  I also like this pattern because it is easy to use once the developer understands it.

Most of you that know me, know that I’m not a purest by any stretch of the imagination.  I’m much more interested in writing testable, bug free, maintainable over time code than adhering to a text book version of a pattern.  As a rule, I would much rather author simple code that works and is maintainable than write complex code that only a few can understand.

When looking at a software solution, it’s best to understand not only the code, but also why the developer wrote the code the way they did.

For the purpose of this series my development context and driving goals are:

  • WPF Line of Business
  • Silverlight Line of Business
  • Software development shop is small with limited resources
  • UI and libraries must fully testable
  • Application users are domain experts but are not computer power users
  • Application is transactional in nature (OLTP)
  • Application stores data in a SQL Server Database
  • Application can connect to the database across the Internet or connected to a local SQL Server Database
  • Application will be deployed in a multi-user environment
  • Application must never allow the user to perform an action that will cause loss of data or to persist invalid data
  • Application must have clean UI that clearly explains error conditions and corrective action

My Articles

I started in the middle of this list and will be filling in the introduction material soon.

NoteI have reorganized the article listing.  I’ve added a new application and the first article for it.  The application uses the Ocean Framework and the source for the framework is included in the application.  The Ocean Code Generation piece will be coming soon.

I’ve decided to place all the source in one post, this way when I update it I only have to update one location.

38 Responses to M-V-VM

  1. ursri says:

    Dear Karl
    Idea would be to store Screen names, control names even commands for similar category in db. Load this info into data, data access classes. Going with M V VM dev model, view model need not be aware of views, would it be appropriate to dynamically load screens? In such case how view model and views classes to be defined?
    Pls suggest.
    Thanks in advance
    ursri

    • ursri,

      Anything is possible. You may want to look at MEF for run-time discovery and loading of assemblies.

      The question is, “is this necessary?” That usually depends on the application requirements.

      This will make the application more complex unless the dynamic loading screens can work in isolation.

      But this is possible and doable.

      Cheers,

      Karl

      • ursri says:

        Thanks Karl for the immediate reply.
        Just got into MEF, yet to study further.

        Lets consider First name(txt), last name(txt), status(combo box), address(txt) are the controls in Candidate and Employee screens. Would it be good idea to store scree_name,screen_control,screen/control_displayname, and associated commands for both Candidate & Emplyee in database and call a generic view-BasicInfoView.xaml for both requirements, dynamically assign displayname & commands to controls? Does MEF address in same line?

        Regards
        ursri

    • ursri,

      If you need dynamic forms I would write a dynamic form generator. Take a look at the Silverlight DataForm control. This generates a form at runtime.

      Dynamic form generators are not that hard to write. They are typically created using some form of metadata. The richer the metadata, the better the generated code will be.

      Example:

      Property: FirstName
      Tooltip: ….
      Max Length: …

      How the form gets generated has nothing to do with how it is consumed ih the UI.

      Once you get your generator working, WPF is so cool that it makes databinding the generated form to a viewmodel an after thought (very easy to do).

      Cheers,

      Karl

  2. ursri says:

    Dear Karl,

    Reg: How efficient would M V VM be with Linq To SQL?

    We downloaded your sample application, found proj/dll s specific to data storage type.
    In our case we are clear about storage type- sql server, do you think that Linq to SQL be better for DAL? if so, (correct me , i am still in learning phase), how best BLL be implemented along with command routing & view model etc…?

    Thanks in advane
    ursri

    • ursri,

      So very sorry for not seeing this comment before today. My bad.

      Data and business layer choice seems to come down to your requirements and what you and your team prefer. I prefer DataReaders and Command objects for interacting with a database. Some use LINQ to SQL other the Entity Framework.

      You should construct your applications so that you can change your data layer without having to change your code.

      If you look at the BBQ Shack, I used IBLL and IDAL. This was a proof of concept.

      In my production applications, I generate all my BLL, DAL code and SQL Stored Procedures, so its no big deal to have the code.

      I would suggest trying different approaches and see which one works best for you.

      Does this help?

      Karl

      • ursri says:

        Dear Karl,

        Thanks for the guidance. Currently working on LINQ to SQL and would try with EF for better FK – relation handling.

        MVVM with relaycommand is time saving feature/functionality. Thinking of binding predicate dynamically. Like providing method – the relay command’s predicate parameter by using method name and reflection techniques – but getting runtime error.
        Could you pls guide in this regard.

        Thanks & Regards
        ursri

        • ursri,

          Not sure I understand your scenario or why you are having a problem.

          If you are having a problem, put your ICommand Execute code in a method and have the RelayCommand call this code. Then you can step though it and figure out the problem.

          Without specifics, I really can’t advise with more clarity.

          Karl

  3. buddybear24 says:

    Has someone written up the differences between WPF and Silverlight in regard to the gap libraries like Prism, Caliburn, and MVVM Light Toolkit are trying to bridge. I would prefer not to use third party libraries to fully implement MVVM in Silverlight, but it appears to be a necessary evil.

    I was hoping someone blogged/documented what is missing so I can make an informed decision. For instance, Silvelight implements the ICommand interface, but to quickly utilize the Commanding functionality you might choose a third party library.

    I am moving from 10 years of ASP.Net/Code Behind to Silverlight/MVVM; since the MVVM “cement” is still a little wet in Silverlight I am trying to determine a best course of action.

    As a follow-up question, if you were going to choose a library to “kick start” your development which would you choose.

    Thanks,

    Jeff

    Your thoughts?

    • Jeff,

      Strongly recommend that you get a firm grasp of thinking in terms of MVVM before jumping to a framework. The change in thinking like I talk about here: http://karlshifflett.wordpress.com/2010/05/09/stuff-wpf-line-of-business-using-mvvm-video-tutorial/ should be your Priority 0.

      What I have found is that me and others write frameworks to solve problems. But if you don’t first understand the problem you are trying to solve, looking at frameworks won’t mean as much.

      I would suggest taking the next few weeks to learn the simple pattern, write some apps and see where you run into things. I like to look at the solutions in MVVM Light, Prism and my own work, as a resolution to a scenario.

      In other words, my scenario is “…” and I used “…” to solve it.

      I’ve been thinking about writing a book that uses this exact format.

      I use the Messenger in Prism because I like they way its written.

      For all my own needs, I write the code myself. If you look at Stuff, you’ll see very little extra code is required.

      I’ll be converting Stuff to Silverlight and adding in support for Amazon.com, books, music, etc. This app will use the MVVM pattern.

      Have a look at: http://www.nikhilk.net/

      Best MVVM video ever recorded is by: Jonas Follesø (http://jonas.follesoe.no/)

      Vidoe link: http://media01.smartcom.no/Microsite/go.aspx?eventid=4459&urlback=null&bitrate=522627

      Cheers,

      Karl

      • buddybear24 says:

        Hey Karl,

        The application I am developing is a Silverlight application getting data from a RESTful service. In the last couple of months I have researched MVVM, Entity Framework, WCF Data Services, LINQ, and Silverlight. As I move from ASP.Net to Silverlight the “bear bones” functionality I need is the Event Driving functionality which is accomplished (I know you know this) through Binding, Properties, and Commanding.

        After reading countless articles on the ICommand Interface it seems most tutorials/blog posts implement a framework instead of “rolling their own”. I did read one blog post by John Papa http://johnpapa.net/silverlight/5-simple-steps-to-commanding-in-silverlight – where he didn’t use a framework, but the code didn’t work for me.

        Side Note: Need to figure how to more effectively debug a Silverlight application. In particular where the events (button clicks) aren’t firing.

        Anyway, it seems the many people are using frameworks to make Silverlight more fully-featured like a WPF application. Prism, Caliburn, and MVVM Light Toolkit appear to be designed to speed up the design process in Silverlight but also because the developers of these frameworks realized the short-comings of the Silverlight Object Model.

        I am trying to identify what those short-comings are. Once I understand that better, than I can make an informed decision as to whether it makes sense to roll my own and fill in the gaps myself or to use a framework.

        BTW…thanks for the links. I am currently watching your video series on Stuff.

        I appreciate your response,

        Jeff

    • Jeff,

      I know its not easy, especially at first. The struggle is worth it. The school of hard knocks is the best school in the world.

      Where are you located?

      Do you have .NET User Groups in your area?

      User Groups are a great resource for all developers, great place to meet new friends too.

      Cheers,

      Karl

      • buddybear24 says:

        Karl,

        I am in Princeton, NJ, work for Mathematica Policy Research. More info – http://www.jeffreylangdon.com

        I do have the Commanding part working, makes much more sense now. I went through almost all of your Stuff videos yesterday, hope to see the rest today.

        I really like what you have done with Stuff. Thanks for all your help. Let me know if you plan to visit the NY/NJ area.

        Would like to go to DevConnections in Las Vegas this year for the Silverlight sessions, but I am taking my family on a Disney Cruise. No regrets. ;)

  4. evilted says:

    Hi Karl,

    I enjoyed your WPF Coffee wizard – it helped me understand a lot about MVVM, thanks!

    I found 2 problems with the approach you gave:

    1) The main view has knowledge of all the other views by fact that you used DataTemplate to map page views to page ViewModels.
    It would be better for a re-usable wizard if the pages were injected externally from the wizard framework and resolved themselves.

    2) This leads on from (1) and is a big issue try to get the code to work in SilverLight.
    There is no DataTemplate method of binding views to ViewModels in SilverLight, so how would you do this?

    I have everything working perfectly except for this issue :(
    I found a cool article authored by Glenn Block on how to bind views to view models but it doesn’t appear to help.
    I think because they use view first approach and have a LocateViewModel method.
    What this requires is a LocateView method or someway to instantiate and show the corresponding view, given the view model.
    Any thoughts?

    Thanks in advance

    ET

    • ET,

      MVVM is a very simple pattern with many implementation patterns.

      Are you injecting your views? If so, you can inject the viewmodel or assign the viewmodel to the views datacontext.

      There are many ways to wire up your application.

      Do your viewmodels have any dependencies that have to be injected or resolved? If so, what are you using for dependency resolution? The answer to these two questions typically drive how your application needs to be wire up. Let me know.

      Karl

  5. evilted says:

    Karl,

    Thanks for the fast response – I’ve been up all night tearing what little hair I have left out :(

    I’m doing things essentially the same as your sample but rather than having a CreateViews method where I create and add all the ViewModels, I have an AddView method. The sample application creates views as user controls with their own ViewModel and calls AddView in the wizard.

    Everything seems to be the equivalent of me REMing out the DataTemplate binding the views to the ViewModels in your example, i.e., I get a text string giving the class path of the ViewModel wrt the namespace, but no pretty view :(

    How can I continue to use the viewmodel first approach that you are uisng and get the view to render?
    Or put another way, how would you get the views to render in your sample if you REM’d out the DataTemplate binding in the main wizard view?

    Thanks

    ET

  6. evilted says:

    i.e., do this:


    <!–

    –>

  7. evilted says:

    Ooops, doesn’t like XML formatting :(

    I mean, remove this part in CoffeeWizardView

    These four templates map a ViewModel to a View.

  8. evilted says:

    I don’t think DataItemsDataTemplateSelector is going to help me, because the main wizard view will need to use this, correct?
    – If so, we are back to problem item #1 in my initial post :(

    “You can also inject the actual logic by adding property and pass your class in that provides the mapping”

    I don’t understand how to do this :(
    Can you please provide an example?

    Thanks

    ET

    • The selector allows you to determine your template at run-time. That’s what you need correct?

      If you look at the code, it returns a datatemplate based on data type. I think this is what you need.

      You don’t have to have properties for the datatemplates you can allow the selector code to return anything you want based on datatype.

      The inject thing was a way to allow another class to determine which UserControl is returned based on datatype. To do this, just addd a property to the selector and set it to the class in XAML.

      Cheers,

      Karl

  9. evilted says:

    Actually I solved it :)

    I changed the wizard to register UserControl as pages instead of the ViewModels, changed the content frame from ContentControl to UserControl and that was it !

    Thanks

    ET

  10. [...] MVVM (Model/View/ViewModel) is an architectural pattern that is well-suited for Silverlight and WPF development. It is a variation of the MVC pattern that was borne out of the development of Expression Blend. [...]

  11. [...] MVVM (Model/View/ViewModel) is an architectural pattern that is well-suited for Silverlight and WPF development. It is a variation of the MVC pattern that was borne out of the development of Expression Blend. [...]

  12. [...] MVVM (Model/View/ViewModel) is an architectural pattern that is well-suited for Silverlight and WPF development. It is a variation of the MVC pattern that originated from the development of Expression Blend. [...]

  13. [...] Karl Shifflett’s blog covering MVVM [...]

  14. [...] relating to the Model-View-ViewModel (M-V-VM) pattern for WPF.  These posts can be found at http://karlshifflett.wordpress.com/mvvm/.  Whether you are new to WPF, new to M-V-VM, or need to develop a WPF Line of Business (LOB) [...]

  15. Hi Karl, I am a newbie in WPF, and Prism. I just saw your blog, and your MVVM training VS extension. I would like to get training in Prism, and you mentioned that you would be publishing something about it, but I guess that you haven’t had time due to your surgery, and many other things keeping you busy. Can you recommend where can I start? I already saw the documentation, but would like something to start building my skills.
    Do you know of any online/classroom training on the subject?

    Thanks!

    Carlos.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 246 other followers