My MVVM article in MSDN Magazine

Finally!  After spending more than 100 hours over several months working on an article for MSDN magazine, it is now published!  The article is about using the Model-View-ViewModel (MVVM) design pattern to create WPF applications.  My ‘WPF Apps With The Model-View-ViewModel Design Pattern‘ article is in the February 2009 issue of MSDN Magazine.  I think it is by far my best, and most important, article yet.   Big thanks go to John Gossman for giving me an in-depth tech review.

Enjoy!

44 Responses to My MVVM article in MSDN Magazine

  1. Paul Kohler says:

    Wow – nice article, very timely too! I am still working on “grokking” the whole WPF MVVM thing and its going well largely due to the articles you have posted over the years.
    Thanks, PK 🙂

  2. Josh Smith says:

    Thanks a lot for the feedback Paul. I hope you enjoy WPF + MVVM as much as I do! 😀

    Josh

  3. hugeonion says:

    Excellent article Josh. I got a chuckle out of the carrier pigeon reference.

    Your blog postings and discussions on WPF Disciples helped motivate me to travel out to Cupertino for the MVVM training Karl Shifflet et al. are giving this weekend. This MVVM stuff is way cool and thanks contributing what you have on the subject. Keep up the great work!


    Christopher

  4. Karl Shifflett says:

    Awesome work!!!!

  5. Tom Deleu says:

    Excellent article! Helps me a lot to understand MVVM.

    But one question arises:
    How would you handle a multi form scenario in this. Now you bind a tabcontrol to the workspaces. You can’t do the same with multiple windows as you have to create and show a window each time, right? (ex. one for each customer you create/load)

  6. Glenn Wilson says:

    Really good article, and well worth the read. I have been following your posts and articles for a while and they are always of a high quality and informative, Thanks heaps.

    Many a time I have swayed back and forth between Windows forms and WPF for my Apps, and just when I need them you seem to come up with a good article.

    Would love to see more business based apps as samples, maybe even one on a method for application security.

    Thanks again.

  7. Great article!

    I had some “aha”-moments when reading it and it was really helpful! Thank you! 🙂

  8. Dylan Smith says:

    Love the article Josh! I’m just getting started with WPF and this helped me alot with identifying some effective UI patterns to use.

    I noticed there was a link in the article to download the source code, but it goes to a File Not Found page. Is it possible for you to post the source on your blog (or just email it to me privately). I’d really like to examine it in more detail to help me better understand exactly how all the pieces fit together.

  9. Weidong Shen says:

    Thank you very much for this excellent article!

    In addition to the sample for that article, could you please suggest some other good C# samples that uses MVVM?

    Thanks again.

  10. Bill Campbell says:

    Josh,

    Excellent article! I have read all of your WPF work and they are all great but this one is the best and most complete. Filled in a lot of holes for me. Understanding how long it took you to put this together makes me realize how much work you put into it. Thank God you weren’t able to do this in a few hours or I would have known that I should change professions!!

    Great Job and Thanks for Sharing!

  11. Benjamin says:

    Josh, enjoyed the article a lot. All of your items have helped me grasp the beauty and power of MVVM+WPF. I enjoy this pattern so much, I get giddy about it!

    As someone else mentioned, the link to the code in your article is throwing a 404. I would like to download it when it becomes available.

    Thanks for your contributions to the community!

  12. Josh,

    thanks for sharing. I would like to ask you some advice… my desktop application is WPF, using MVVM. But now i need expose a part of it on web. I would like to use ASP.NET MVC… do you have some tips to make my viewmodel friendly to asp.net mvc ? I know it is Silverlight friend 🙂

  13. Raul says:

    Josh,

    AMAZING article, as usual… you are a model to follow… amazing concepts… I was stunned after read it… thanks for sharing your work… but for some weird reason i cant download the code… can you provide a mirror here?

    Thanks a lot.

    Raul

  14. Josh Smith says:

    Thanks a lot for all your great feedback. I’m sorry for the delay in my responses these days, but my girlfriend and I are on vacation in Hawaii.

    I have informed MSDN Magazine about the broken link to the source code download. I will notify you once the link is fixed. Thanks for your patience.

    @Tom – Having a Window open, instead of a TabItem, would require more code to keep the ViewModel and Views in sync. You’d need code that opens and closes the windows, which is not necessary when working with TabControl.

    @Weidong – For more C#/MVVM goodness, you should also check out my Crack.NET app at http://cracknetproject.com

    @Paulo – Sorry, I am not sure how the MVVM pattern would work in an ASP.NET MVC application. That would definitely be an interesting thing to read about… 😉

  15. Josh Smith says:

    I just tested this link out, and found that I could download the source code without a problem:

    http://code.msdn.microsoft.com/mag200902MVVM/Release/ProjectReleases.aspx?ReleaseId=2026

    Josh

  16. Benjamin says:

    Yep, the link works now, Josh. Thank you for making a version available for us VB users, too!

  17. Josh Smith says:

    Benjamin – The VB version was created by MSDN Magazine, not me. They recognize the importance of providing helpful material to their readers, in their language of choice. That magazine is top-notch. 8)

    Josh

  18. Raol says:

    Thank you for the great article!
    I used MVVM in my application and ti was so easy.
    But let me share my knowledge on objects validation.

    My business objects are validated with Visitor pattern and validator returns Dictionary. Dictionary keys are properties names of the business objects and values – errors respectively.
    So it is easy to return error for each property from IDataErrorInfo[].

  19. Matt says:

    Hi Josh,
    Great article. One question that I have been unable to find a straight answer on (or sample app for) is the use of Entity Framework in a M-V-VM WPF app. Are you able to shed some light on how one may structure their solution if EF was to be used?
    Based on Figure 11 in your article I assume the Customer Class could be one of the many Entity Objects code-gen’d in the EF Data Model. Where, then, should LINQ to Entity be used to CRUD the Objects?
    Any help is much appreciated,
    Matt

  20. Ipek says:

    Hi Josh,

    As everybody said it’s a great article like all of your previous works. I have learned a lot from your articles and samples.

    But I need a suggestion about one thing that always confuses me when struggling with patterns. I have developed a WPF application which uses a Presentation Model, I guess :). I have a presenter for each view where each presenter knows its view as much as the view’s interface. Presenter takes it’s view and model from constructor paremeters and then whomever created the presenter calls the Start method of the presenter to attach presenter to the view which eventually sets the view’s DataContext to the given presenter. So the view is also aware of its Presenter.

    While there wasn’t so much information about MVVM, I decided to use this approach by analyzing Prism in order to implement a kind of “ViewModel” for my views. Now I want to use MVVM but I’m stumbling upon the same problem everytime: I need to save my model and in order to do that I have SaveCommand with CanExecute method (currently in Presenter but will be in ViewModel in MVVM). When CanExecute returns true the document can be saved but it needs to get a FileName if it’s empty. Since getting a FileName is a UI implementation it needs to be in the UI (I’m using a SaveDialog but it can be implemented in different ways). So when we use MVVM we don’t know about the view therefore can’t ask it to get the file (which I’m doing right now, through the method defined in view’s interface which Presenter knows), then how do we do it? With events? These problematic situations arise when the parameter needed by the VievModel doesn’t have an open representation in view like a TextBox.

    So, which is the right way to do these kind of interactions with the view without knowing the view?

    Thanks in advance

    Ipek

  21. Nick says:

    Great article, Josh. I was playing around with WPF 4-5 months ago but only recently took an interest in it again. I downloaded the source and attempted to make modifications so that customers could be removed.

    It only took me 20-25 minutes to make the necessary modifications following the pattern you put forth with the add functionality. However, I did have one question.

    In order to remove the appropriate customer view model from the AllCustomers property in the AllCustomersViewModel class, I created the following method:

    void OnCustomerRemovedFromRepository(object sender, CustomerRemovedEventArgs e)
    {
    AllCustomers.Remove((from CustomerViewModel cvm in AllCustomers where cvm.FirstName.Equals(e.RemovedCustomer.FirstName) && cvm.LastName.Equals(e.RemovedCustomer.LastName) select cvm).ElementAt(0));
    }

    Now, this works, but I was wondering if there was a better way to get the appropriate customer view model corresponding to a customer (e.RemovedCustomer in this case). I did some tests, and if there are two people with the exact same info, the first one will be removed from the system and I just don’t see a way around it.

    Thanks in advance for any response!

  22. Mohamed Afifi says:

    Hi Josh,

    I would suggest that Microsoft creates a new product called JSDL (Josh Smith Developers Library) and distribute it with Visual Studio instead of MSDN. I am sure they will achieve higher customer satisfaction by doing this 🙂 You are excellent!! I hope you are enjoying your vacation with your girl friend. I am sure she knows WPF much better than all of us 🙂

    I have some questions:

    -All MVVM examples and articles I have seen say almost nothing about message boxes and dialogs although they do exist in almost every non-trivial windows application. Imagine that when closing your CustomerView tab item you want to ask the user whether or not she wants to save her work, wait for her do decide, save the customer if she wants and then close the tab item. Of course, you cannot put this functionality (asking the user to save or not) in the CustomerViewModel as it is UI specific. One UI might display a message box whether another UI implementation might just display the question in some area of the main UI. So, how to implement this in the view? I thought that I could raise an event from the CustomerViewModel and handle it in the view then the view asks the user in the way it wants but in this case we will need a code behind file that I am trying to avoid. Also, how can the viewmodel wait for the user to click “Save” or “Don’t Save” before it continues and closes the tab item?

    The same issues will appear if we want to implement your Options menu item to display an ApplicationOptionsViewModel. One UI might display this as a dialog while another might display it as another workspace in a tab item like the project properties in Visual Studio.
    I would appreciate if you can advise on this.

    -Would you please tell me about the ideal situations where it is a must to have a code behind file?

    -Can you please tell me when should I use RelayCommand and when to use something like your CommandSink implementation? You are very convincing on the two. The result is that I am very confused 🙂

    -Are you always using “this.” And “base.” Just for readability or there is another reason?

    Thanks a lot for your time and sorry for not being concise enough.

    Regards
    Mohamed Afifi

  23. Günter Schwaiger says:

    Excellent article!

    It would be very interesting for me to see how to implement an Edit command in the ViewModel. How would the the Execute method be called when double clicking the ListViewItem? Could this be done in XAML without an event handler?

    Thanks in advance,

    Günter

  24. Antonio says:

    Very good article Josh,
    I am trying to get some idea from your work but I am struggling on how to implement common UI elements among workspaces. I mean, I would like to have a toolbar with some logic on enabling/disabling buttons and firing commands to be used for example for a CustomerView and for a VendorView, how would you implement this using MVVM pattern?
    Thanks
    Antonio

  25. Josh Smith says:

    Matt,

    Using EF as the Model in an MVVM architecture should not impose any significant changes to the example application associated with my MSDN article. MVVM is all about abstracting away the underlying data model so that WPF’s binding and commanding support can easily consume it. All of the CRUD operations would remain outside of the ViewModel classes, leaving them as an implementation detail of the Model. With that said, I have never actually used EF as the Model in an MVVM application, so there might be some gotchas of which I am not aware. Please let me know what those are, if you happen to encounter any.

  26. Josh Smith says:

    Ipek,

    One common approach to showing dialog boxes (such as messagebox, save-file dialog, etc.) is to implement it as a service, like in CAL (aka Prism). You create a class that any ViewModel can use to request some piece of information to be shown to the user (i.e. messagebox) or taken from the user (i.e. file path from save-file dialog). The service can provide a default implementation for each action, such as showing a plain old SaveFileDialog when asked for a file path. Also, when a View loads it can register a provider for that service, so that the View’s service provider is used while it is being shown on the screen.

  27. Josh Smith says:

    Nick,

    In a real app, the Customer class would probably have a unique identifier associated with it. You could then compare the CustomerViewModel’s ID property to find the correct object(s) to remove. Alternatively, the CustomerViewModel class could expose its underlying Customer object via a property or method, and then you could simply use a reference comparison to find the ViewModel object(s) to remove.

  28. Josh Smith says:

    Mohamed,

    Thanks a lot! I’m glad you find my article so helpful. 🙂

    Please read my response above to Ipek for my thoughts on how to have the ViewModel indirectly make use of things like dialog boxes.

    Your question about how to display the same ViewModel classes in different types of Views reminds me of this article I wrote a while back: http://www.codeproject.com/KB/WPF/podder3.aspx That article isn’t about MVVM, but the idea is close enough. If you are triggering the UI to be shown in response to a menu item being clicked, you will have to have some class that decides whether or not to open a separate dialog box to show the ViewModel UI. Perhaps have the ViewModel classes implement an interface that provides an indication of where/how the UI should be shown?

    Code-behind files are OK in my book. After all, it makes sense to put code in a code-behind file. The question is what should go in them. 🙂 My answer to that question is that any code particular to a View, such as using its resources or modifying its UI elements or responding to an event on its ViewModel, belongs in the code-behind. If you find that the code-behind files have a lot of similar code in them, perhaps it’s time to abstract that logic into an attached behavior. http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

    Use CommandSink if you must use routed commands. Otherwise, use RelayCommand. Routed commands should not be your first choice when choosing how to set up commanding, because it’s unnecessarily complicated and heavy for most use cases.

    I use the ‘base’ keyword when referencing a member of the current object’s base type, just for clarity.

  29. Nick says:

    Thanks for your response, Josh! Very helpful.

  30. Josh Smith says:

    Günter Schwaiger,

    What you are asking about is a perfect scenario for using attached behaviors. In addition to the link I provided Mohamed about attached behaviors, you should also check out this one: http://blogs.msdn.com/johngossman/archive/2008/05/16/attachedbehavior-pattern-sample.aspx

  31. Josh Smith says:

    Antonio,

    Your question is pretty vague, so it is difficult for me to provide a concise answer. However, I will say that if you have a toolbar whose buttons manipulate the “current” ViewModel object (perhaps, the object being edited) then the commands tied to those buttons should ask the ViewModel object to handle the can-execute and execute logic for them.

  32. Günter Schwaiger says:

    Thanks a lot for the link.

  33. Antonio says:

    Hi Josh,
    This morning I wake up early (4:12) with something running on my mind and I got it!
    I created a new ViewModel inherited from the WorkspaceViewModel adding all commands properties to be managed by the toolbar buttons. I bound the toolbar buttons command property to these commands and in the let’s say VendorView I just had to add the toolbar and everything worked!!!
    Obviously the VendorViewModel inherit from the new created ViewModel.
    Fantastic!
    Thank you very much to open my mind to Wpf and MVVM.
    May I send the project I created to you to see if I really got it or I did something wrong?
    Thanks
    Antonio

  34. Jerry Lin says:

    Hi Josh,

    Thanks for writing this article, it’s really helped me to get a better feel for how to do MVVM in my own projects.

    However, I was hoping you could clarify a minor point for me. In MainWindowResources.xaml, I’m confused about the TabControl that is bound to the WorkSpaceViewModel collection. It is set up so that its ItemTemplate refers to a DataTemplate that ultimately renders each generated TabItem’s header. This confuses me as I always assumed when an ItemsControl is bound to a collection, setting the ItemTemplate tells WPF how to render the UI for the underlying objects, in this case the WorkSpaceViewModel instances.

    Is my understanding of how to use databinding collections flawed?

    Jerry

  35. Josh Smith says:

    Jerry Lin,

    TabControl has two properties that can be used to customize the display of each TabItem. The ContentTemplate property can be used to render the TabItem’s content, and the ItemTemplate can be used to render the TabItem’s header. Both templates have a DataContext of the ViewModel object represented by that TabItem, so both can bind to it.

  36. Johnny Q. says:

    Hi Josh. Great article. I have a question: would you advise to drop all the ApplicationCommands (like Open, Cut, Copy, etc.) and use delegate commands instead? And how could one attach a shortcut to a delegate command, to keep it as similar as possible to the ApplicationCommand it substitutes?

  37. Johnny Q. says:

    Another question :). What is in your opinion the best way to handle situations like this: you have a dialog (to display, say, properties of a model class) backed by a ViewModel. In the ViewModel you have a delegate command which operates on the model. You want that the same control that executes a command exposed by the ViewModel to operate on the view as well (like closing the dialog when pushing the Save button). Should the ViewModel have a reference of the view in this case?

  38. Mohamed Afifi says:

    Josh, thank you very much for your kind response.

    I have read the 3 articles you posted about podder. I am really facinated. I still have to study CAL in details (never used it before)to figure out how they handle message boxes and dialog boxes with MVVM.

    It would be great if you can post an example on this topic as well as using multi-threading for background tasks in ViewModels.

    Thanks a lot.

  39. Ipek says:

    Thanks for the helpful reply, Josh.

    I started to migrate my app to MVVM but I’ve faced so many problems. The most important one is the typed DataTemplates. I didn’t realize that injection of the necessary view by DataTemplates was managed by reuse of templates.

    The app I’m developing is for simulating a machining operation. It isn’t so big right now but it has some very complex UI. I’m using tabbed document interface and since there is one view control created for all the same type of documents in each tab, while I’m switching tabs the views render slowly because of all the rebinding after DataContext change. For example: I have one document type which is using graph control that is a Windows control. And every time I switch tab everything is redrawn on the control.

    In my app there won’t be too many documents open at once but when there are three or four I don’t want the transition from one to other to be that slow.

    Is there a way to overcome this problem? If I should create a View explicitly for each document as I do for ViewModel, where and how should I do it?

    Or is something wrong with my views that I’m facing this slowness?

    Thanks a lot Josh.

  40. Maxx Daymon says:

    Congratulations on an excellent article!

    One note I would make is that I have personally seen the “ViewModel” suffix cause more grief than help. The “Model” refers to the *set* of classes that make up the “model” and the ViewModel refers to the *set* of classes that make up the ViewModel (where the model isn’t sufficient), so the suffix does not logically describe what the class actually is.

    For example, a model would contain classes like Person, Address, FileInfo, and so on (note: not named PersonModel, AddressModel, FileInfoModel, CustomerModel, etc.)

    Likewise, the ViewModel, that is, the set of classes that adapt the model to the view, contains classes such as CollectionView (a class in the ViewModel over a Collection), XmlDataProvider (a class in the ViewModel that adapts raw XML to a form consumable by the UI, and so on.

    In the end, the problem stems from naming entities in the ViewModel as if they *are* the ViewModel. I have found that some people are able to absorb the pattern more quickly, and use the pattern more effectively, when this confusion is removed. Naming classes after what they are and do tends to be more helpful (Provider, Adapter, View, etc.)

    To give a parallel analogy, if you call a set of “people” (classes) a “group” (model), then it’s very confusing when you suffix each person with the entity they are a member of (JoshGroup, MikeGroup, SusanGroup)

  41. Joy says:

    Ragarding the your reply to Gunter about Editing.

    I check the link given by you.
    http://blogs.msdn.com/johngossman/archive/2008/05/16/attachedbehavior-pattern-sample.aspx

    Seems bit complex.Do you have any working MVVM sample which have edit feature?

  42. Al says:

    Hi Josh,

    Thanks for another great article. Just curious, how do you handle updating the ViewModel when something in the Model changes? For example, the Model automatically formats a specific property when its value is set/updated. (Set the first letter in the last name to uppercase.)

    Al

  43. Rico Alexander says:

    Josh, how would you handle multiple selections using the XamDataGrid. I need to track in the view model which items and/or fields are selected at any giving time. Thanks.

  44. Mark says:

    Josh, could you elaborate on the following remark you made in a reply to a question by Mohamed on February 2?

    “Use CommandSink if you must use routed commands. Otherwise, use RelayCommand. Routed commands should not be your first choice when choosing how to set up commanding, because it’s unnecessarily complicated and heavy for most use cases.”

    I have been told that programmers at my company will be using one of these two ways of handling commanding as the standard that will be used when doing WPF. At this point I really don’t know enough about routed events to suggest one over the other. One specific question that I do have is under what circumstances must RoutedCommands be used?

    Thanks and great article!