M-V-VM

Last Updated: 1-28-2009

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.

References

Hope you have a great day!

Just a grain of sand on the worlds beaches.

58 Responses to “M-V-VM”

  1. WPF M-V-VM Series Begins « Karl On WPF - .Net Says:

    [...] M-V-VM [...]

  2. JAPF » Blog Archive » Learn Model-View-ViewModel, LOB WPF/Silverlight application Says:

    [...] is a WPF guru, and he just started a new series of articles on Model-View-ViewModel. Here is his own introduction: “My goal is to provide an [...]

  3. 2008 December 12 - Links for today « My (almost) Daily Links Says:

    [...] Karl Shifflett announces his WPF M-V-VM Series Begins which links out to the WPF & Silverlight Line of Business UI Design Pattern Home Page [...]

  4. zellen Says:

    Great start Karl. Can’t wait til you get to the WPF Line of Business Introduction and the new release of the XAML Power toys. I have a question on the Power Toys. Are you planning on having the same approach as when you create LOB Forms i.e. you select an entity and then get the corresponding VM?

    /Johan

  5. Karl Shifflett Says:

    Zellen,

    Yes, XAML Power Toys updae will support nested class structures.

    Cheers,

    Karl

  6. zellen Says:

    With support for nested classes do you mean creating a VM for each childcollection or a property on the vievmodel like: ObservableCollection orders, a collection of OrderViewModels or a OrdeListViewModel property??

  7. Karl Shifflett Says:

    Zellen, What are you referring to? XAML Power Toys?

    Karl

  8. zellen Says:

    Yep. The reason i’m asking is because it would be nice to hear about how you structure your app regarding your viewmodels… Like one per entity, viewmodels inside viewmodels and so on…

    /J

  9. Karl Shifflett Says:

    Zellen,

    My app structure depends. I have a few more example apps I’ll be posting soon.

    Cheers,

    Karl

  10. JAPF » Blog Archive » Why should I use Model-View-ViewModel pattern Says:

    [...] Karl Shifflett started a series about MVVM, you can find his work here. [...]

  11. zellen Says:

    Hi. This might be a dumb question but I’m just wondering how you create a RelayCommand in c# that takes a parameter. In your VB projects you just type AddressOf SaveSomething and have a method like SaveSomething(ByVal param As Object) and bind to it from your xamlpage using commandparameter. Whats the equivalent in c#??

    /J

  12. Karl Shifflett Says:

    Zellen,

    Glad to help with the question:

    Lot’s of good C# MVVM examples in this application:

    http://karlshifflett.wordpress.com/mvvm/internationalized-wizard-in-wpf-using-m-v-vm/

    The above application has both C# and VB.NET code.

    Cheers,

    Karl

  13. zellen Says:

    Yes I have gone through it already, but that one doesn’t use commandparameter in any of the xaml-pages. The difference seems to be with creating the RelayCommand. In c# it’s

    new RelayCommand(
    () => this.LoginExecute(),
    () => this.CanUserLogin());

    where you have to match against the signature of private void LoginExecute().

    In vb you just seem to point at the method using its name and not the parameterlist using AddressOf LoginExecute

    New RelayCommand(
    AddressOf LoginExecute, AddressOf CanLoginExecute)
    /J

  14. Karl Shifflett Says:

    Zellen,

    The RelayCommand constructor is looking to match method signatures.

    Since the Execute method takes a single parameter of Type Object and the LoginExecute method will have a single parameter of Type Object this works.

    What you see Josh doing sometimes in the Wizard program, is to supply a Lamda expression or Function in the constructor.

    You can also check out Josh’s Crack.NET program on his blog, http://joshsmithonwpf.wordpress.com for more great C# MVVM and RelayCommand examples.

    Cheers,

    Karl

  15. zellen Says:

    Maybe what i’m looking for is how you rewrite this lambda-expression

    new RelayCommand(
    () => this.LoginExecute(),
    () => this.CanUserLogin());

    …so you can do…

    private void LoginExecute(object param)
    {
    //do something with param
    }

    /J

  16. Karl Shifflett Says:

    Zellen,

    I’m not fluent in C# yet. The best I can suggest, is to look at the examples I’ve referenced.

    Karl

  17. zellen Says:

    Which is a good thing!
    A person who is fluent in c# probably spend too much time in front of the computer anyway… :-)
    Thanks for your patience with me…

    /J

  18. johanjvr Says:

    Hi Karl,

    I’ve found that the _canExecute method is continuously executed even when I close the UI that I’ve added the commands to. I found that when your implement the IDisposable interface and set both the _execute and _canExecute methods to null the problem are resolved.

    Regards,
    Johan J v Rensburg

  19. Karl Shifflett Says:

    Johan,

    I’ve seen this too also.

    Do you have a sample project I can look at to work this issue?

    Cheers,

    Karl

  20. Johan Says:

    Hi Karl,

    All I had to-do to fix this problem is to implement the IDisposable Interface (in the RelayCommand class) and then when ever I close my UI now the commands are all disposed, and does not execute again.

    Here is the code example:

    #region IDisposable Members

    public void Dispose()
    {
    _execute = null;
    _canExecute = null;
    }

    #endregion

    Regards,

    Johan J v Rensburg

  21. Beth Massi - Sharing the goodness that is VB : WPF Drag-Drop Data Binding on dnrTV & WPF Business App Resources Says:

    [...] WPF & Silverlight Line of Business UI Design Pattern Home Page [...]

  22. WPF Drag-Drop Data Binding on dnrTV & WPF Business App Resources - VB Feeds - vbCity Sandbox Says:

    [...] WPF & Silverlight Line of Business UI Design Pattern Home Page [...]

  23. 4 WPF Junkies (WPF & Silverlight Line of Business UI Design Pattern Home Page) - henryjwr Says:

    [...] anda memang junkies terhadap WPF jangan lewatkan untuk mengunjungi Site ini "WPF & Silverlight Line of Business UI Design Pattern Home Page" by (Karl Shifflett)Banyak hal menarik yang mungkin dapat membantu kita.  NB: Tapi [...]

  24. sichere WPF-Applikationen mit user/role/permission | hilpers Says:

    [...] dabei gut, um Anpassung in jeder Richtung vorzunehmen. Einiges finest Du dazu bei Karl Shifflet (http://karlshifflett.wordpress.com/mvvm/) Bei der Implementierung der Sicherheit kann man sich an das ASP.NET Modell anlehnen, z. B.: [...]

  25. Ocean Framework Released - MVVM for WPF Line of Business Update « Karl On WPF - .Net Says:

    [...] M-V-VM [...]

  26. Karl Shifflett’s M-V-VM series for WPF/Silverlight Says:

    [...] 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) [...]

  27. links for 2009-01-27 | graemef.com Says:

    [...] M-V-VM « Karl On WPF 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. (tags: development patterns wpf mvvm) [...]

  28. WPF and the Model-View-ViewModel Design Pattern at Inveigled By Design Says:

    [...] 2.  Karl Shifflett’s MVVM page on his blog:  Karl on WPF [...]

  29. bgrosse Says:

    Karl, all of your posts regarding MVVM have been greatly helpful to me! Thank you! One area I’m running up against that I’m unsure of:

    How can the View take an action based on ViewModel event. For instance, when my ViewModel object becomes IsSelected, how do I call BringIntoView on my XAML view? Does that make sense?

    Binding from a ViewModel property to a View property is easy. But how do you execute UI code such as BringIntoView based on events in the ViewModel? I can think of some hacks that could accomplish this, but I want to know the “right” way of doing it.

    Thanks for any input you have!

  30. Karl Shifflett Says:

    bgrosse,

    Nice question.

    Without full context of the application and structure of the code one thought is, you could raise an event on the ViewModel, handle it in the View.

    Cheers,

    Karl

  31. bgrosse Says:

    Karl, thanks so much for the response! So your suggestion would be to handle the VM event in the View code-behind?

    Here’s a little more context, that perhaps complicates the issue and seems to me to make that solution a little more difficult:

    - I have an ItemsControl in a ScrollViewer showing a list of transactions. The ItemsControl.ItemsSource is bound to a TransactionsVewModel that exposes a ListCollectionView of TransactionViewModel’s.

    - The DataTemplate for the ItemsControl holds a ContentControl (basically serving as my item container). The DataTemplate for that control is dynamically switched depending on TransactionViewModel.IsBeingEdited (following the pattern used by Dr. WPF in his IEditableCollectionView sample).

    - When the user hits the Down key on the keyboard, I have an input binding on the ItemsControl that calls the MoveNext command on my TransactionsViewModel that selects the next transaction in the ListCollectionView. This all works great… except, when the user hits down enough times that the selected item is off-screen, I want to call BringIntoView on the ContentControl for this TransactionViewModel so the ScrollViewer scrolls down.

    So basically, I need a way to wire up a Selected event on the TransactionViewModel to the BringIntoView method on the ContentControl containing that View.

    I’m not sure how well it would work to try to do this in the code behind, because it seems like getting a reference to the ContentControl that is housing the off-screen VM might be sketchy, especially since this is a virtualizing ItemsControl. So I was thinking ideally I need to wire it up in the XAML.

    The only idea I had so far was to use some attached properties similar to Marlon Grech’s ACB library to ‘connect’ an event to a method. The attached property handler would subscribe to the specified event, and when it fires, would lookup and invoke the specified method (using reflection). I think this might work, but if there is a better/proper way… I definitely want to know about it. Or, if the fact that I’m up against this problem indicates that I’m going about it in a fundamentally wrong way, I want to know that now instead of working around the warning signal. :)

    I know the easy answer is just use a ListBox instead of an ItemsControl and let it handle all this key-navigation and scrolling stuff. I guess that is an option, but I ran into a few road-blocks going that direction. More importantly, I’m really wanting to learn how the MVVM pattern applies to this underlying issue of triggering UI-layer action based on VM-layer events–when it’s not a simple property-to-property binding.

    Any input from you or the other WPF disciples on how this problem is solved in the MVVM pattern would be greatly appreciated!

    Thank you so much for your time!

    —Benjamin

  32. motif8hope Says:

    Karl,
    .I attended the Education Day: Creating WPF Line of Business Applications (M-V-VM) Using C# and VB.NET held on the HP campus last week and it went a long way in helping me to implement my current application using MVVM, so thanks alot all the work is very much appreciated! I asked Jaime during a break about getting the source code to the Southridge application that was displayed (the app included functionality that I desperately need!) and he said that it would be ready for download sometime this week and to check his and your blogs for the update information. I was wondering if that download is going to happen soon. BTW, I just starting using your XAML Power Tools and really like it. Thanks again for all your effort it has been quite a leg up for me.

  33. berndbeekes Says:

    Karl,

    I like the work you have done with MVVM and the Ocean Framework. I would like to use your ideas with a slightly different user interface (central Menu/Ribbon, …). With respect to the demo application think of “moving” the New/Save/Delete ToolButtons to the file menu or a Toolbar in the main window. This results in a problem with the MVVM pattern (commands would have to “cross the border” of a ViewModel).

    How would you solve this?

    Thanks

    /BB

  34. Karl Shifflett Says:

    BB,

    Have a look at this appliction Jaime just posted:

    http://blogs.msdn.com/jaimer/archive/2009/02/10/m-v-vm-training-day-sample-application-and-decks.aspx

    Does this answer the question?

    Cheers,

    Karl

  35. Karl Shifflett Says:

    motif8hope,

    Jaime just posted the application here:

    http://blogs.msdn.com/jaimer/archive/2009/02/10/m-v-vm-training-day-sample-application-and-decks.aspx

    Thank you for you kind remarks and we so glad to hear you got a lot from the training day.

    Cheers,

    Karl

  36. MVVM Pattern for Silverlight « vincenthome’s Tech Clips Says:

    [...] WPF & Silverlight Line of Business UI Design Pattern Home Page [...]

  37. berndbeekes Says:

    Karl,

    I’ ve looked at Jamies’s app, but I had thought of a more “purist” approach (Jamie didn’t put the ribbon into a view). I’m currently thinking sort of a “compound view”. Let my try to explain (don’t know if it works):

    There would be the “main window view” with menu, ribon, toolbar, … and a tab control

    The app would start with an empty window/tab control and the main view bound to a correspondig view model.

    Commands in the main view model would populate the tab control with tab items hosting other views (user controls)

    The “active” tab item/view would be combined with the main view to a “compound view” and bound to a correspondig view model (with the code for the main view inherited from a base class).

    The difficult part ist to “change” the view model when switching/closing tab items ….

    Do you think that this will work?

    /BB

  38. Model View ViewModel ( M-V-VM ) | Dev @ Work Says:

    [...] http://karlshifflett.wordpress.com/mvvm/ [...]

  39. Intro to WPF MVVM « Christopher Hujanen’s .NET Developer Blog Says:

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

  40. Karl Shifflett Says:

    BB,

    This is the beauty of programming, .NET, WPF and MVVM. A problem that can be solved many ways. We all look at problems and solutions differently. so do what works for you.

    Over time, you’ll see many different patterns and solutions emerge and possibly will be posting solutions yourself. I like to take patterns out for a test drive, see how they solve my current problems and go from there.

    My guidance to anyone is, “KISS” Keep It Super Simple. For the most part, simple designs are the way to go. When the occasional problem raises its head that requires some complexity, then go for it. In the end, you’ll be happy you kept things simple except where it did not make sense.

    Cheers,

    Karl

  41. shahbour Says:

    Hello Karl,

    Thanks for blogging the MVVP pattern , i trying to follow up with it, but right now i got stuck at a place.

    I am using FluidKit , to rotate between some items and i need to access on the elements in the view to apply the translate.

    Is there any way to do that, or this will break the MVVP.

    BR

  42. bladebunny Says:

    Karl,
    Great stuff! I’ve much enjoyed reading your work – as well some of the folks to whom you refer. Architectural patterns are very much on my mind as I’m neck deep in development of a Silverlight LOB.

    One area where I’ve seen light coverage — and hope you might expand upon — is in respect to coordination inside of a multi-view app with MVVM. Most examples I’ve seen assume the case where you may have only 1 or 2 views. What are your thoughts on how to manage a Prism style app where you might have controls or views embedded within other views? And you need to coordinate events or changes across other ViewModels? In my own case I’m currently doing most of the coordination using singleton data and event services. But it really seems the model needs a Controller in places. Are you using a sort of MVVM-C pattern where you introduce a controllers to handle this coordination or am I missing something fundamental in the pattern?

    I know I’m probably not asking this clearly enough — I don’t seem to have the language to fully describe it. I guess the gist of it, put another way, would be — how do I avoid having to introduce some sort of God class on app start-up that knows about all the top-level View/ViewModels and handle the coordination, mostly of events, between them?

    thanks and keep up the excellent work!
    tim

  43. Beginning MVVM: The Basics « Mehroz’s Experiments Says:

    [...] Beware, MVVM is quite addictive. Karl Shifflet presents some great MVVM resources on this page. Be sure to bookmark that page for new MVVM [...]

  44. Karl Shifflett Says:

    Shahbour,

    Sorry I missed your comment.

    I’ve not used FluidKit so I can’t give you the best advice on it. Possibly contact the author, since they probably use MVVM also.

    MVVM is a pattern, so you can’t break it. I use it as a guideline and not hard and fast rules. There are times when you need code in the UI, it’s OK.

    Cheers,

    Karl

  45. Karl Shifflett Says:

    Tim,

    I’ve not worked with PRISM so I can’t comment on it.

    Jaime Rodreguez and I will post an example application that uses the concept of a controlling ViewModel. I think this will answer most of your questions here.

    Cheers,

    Karl

  46. bladebunny Says:

    Looking forward with interest. Of course, my main point wasn’t so much about PRISM — as I am trying to avoid the overhead of using it. I’m sort of approximately something similar using a lightweight inversion of control container for dependency resolution between viewmodels. I then also publish/subscribe to some app-wide events that other viewmodels might be interested in. Finally, I’m using a set of gateway/singleton services for managing my objects as well as currently selected object of each type of interest. I’m trying to get to a design where:
    1) Models only know about their entities
    2) Viewmodels know about their models — and they maintain a connection to a view interface
    3) Views are passed their viewmodels on creation — but only know about the bindable surfaces in the VM

    Trying to eliminate any dependency between viewmodels but it seems difficult to do without a lot of application-wide static objects in the cases where you have views within views…..

    tim

  47. MIX09 Videos, Oslo, Cloud Memory and More « Tales from a Trading Desk Says:

    [...] More M-V-VM – Ocean [...]

  48. [MVVM + Mediator + ACB = cool WPF App] – The MVVM « C# Disciples Says:

    [...] – WPF & Silverlight Line of Business UI Design Pattern by Karl Shifflett [...]

  49. M-V-VMパターンについてのエントリを訳してみた 原題:”WPF patterns : MVC, MVP or MVVM or…?” - SharpLab. Says:

    [...] M-V-VMパターンについての具体的な記事を見たい場合は、M-V-VM « Karl On WPF – .NetというページにM-V-VMについて書かれた記事が纏まっているので、これも参照すると良いかもしれません。また、Patterns: WPF Apps With The Model-View-ViewModel Design Patternという凄く面白そうな記事がMSDN Magazineの2009-02号に出ているので、少し待てばこれの日本語訳も出てくるでしょう。ちなみにこのMSDN Magagineの記事の著者はCrack.NETを作られた方でもあるようで、Crack.NETはM-V-VMパターンの良いサンプルコードになっているらしいです。 [...]

  50. kevin Mocha - Model-View-ViewModel Says:

    [...] & Silverlight Line of Business UI Design Pattern Home Page http://karlshifflett.wordpress.com/mvvm/   (*****) Wednesday, 15 April 2009 22:01:29 UTC      Comments [0] [...]

  51. basjl Says:

    Karl,

    First off thanks for the information that you conveyed in Los Angeles at the WPF for LOB class. Awesome.

    You and I talked about a Time Input control for WPF that you wrote. It could be configured to do AM/PM time as well as military time among other things.

    Do you have time to post it now that you’ve posted the class notes?

    Thanks,

    Bill Ashton

  52. Karl Shifflett Says:

    Bill,

    I can’t find the TimeControl code. I’ll keep looking for you I may have written this for ASP.NET and not WPF.

    Cheers,

    Karl

  53. Mike Says:

    Karl,

    I have a question about your demo application.

    It seems that the view is recreated each time you switch between tabs. If the view is not trivial it may take some time for the runtime to render it. You will also lose your UI state (if you’ve scrolled down the list you’ll be back at row 1).

    I wonder if you have any ideas on how to make the views stay alive to avoid recreation overhead and maintain their visual state that’s not necessarily databound to their view models?

    Thanks,

    Mike

  54. Karl Shifflett Says:

    Mike,

    You are correct. This is a feature of the TabCotrol. If you need the individual TabItems to maintain their VisualTree when no selected give this solution a look:

    http://eric.burke.name/dotnetmania/2009/04/26/22.09.28

    You can also not use the TabControl, still keep the content in the VisualTree but move the content out of view and brining in the new content into view. SouthRidge example does this.

    I need to write an application that does this.

    Thank you for the feedback.

    Cheers,

    Karl

  55. pauloquicoli Says:

    Hi Karl, well, let me introduce myself. I’m Paulo Quicoli, from Brazil, and here at job, we are going to start a new project, and for UI i choose WPF. I’ve following WPF disciple list, and learning a lot. I noticed questions about how handling View calls from a ViewModel. I know about other project, called mvcsharp. It implements a MVP pattern, working for asp.net, silverlight, windowsforms. There, they found a good solution for that, a concept of Tasks and Navigation, please, if you get some time, take a look, maybe some ideas from there, can help us, M-V-VM users :)
    Project link is: http://www.mvcsharp.org/

  56. Mike Says:

    Karl,

    Thanks for the info. Eric’s solution is pretty slick. IMHO, that’s how TabControl should work, can’t imagine why would anyone want the visual tree recreated each time you switch between tabs.

    - Mike

  57. Karl Shifflett Says:

    Mike,

    Youre welcome. Keep in mind that “one size does not fit all”

    The default TabControl has its place, but I’m glad you found a solution for your problem.

    Cheers,

    Karl

  58. davebouwman.com » Blog Archive » Pragmatic Choices: Bye Bye Silverlight Says:

    [...] there is lots of talk about Model-View-ViewModel as “the” design pattern to use, yet the Prism guidance does not show [...]

Leave a Reply

You must be logged in to post a comment.