Search code examples
.netwpfmvvmviewmodelreusability

How reusable should ViewModel classes be?


I'm working on a WPF application, and I'm structuring it using the MVVM pattern. Initially I had an idea that the ViewModels should be reusable, but now I'm not too sure anymore.

  • Should I be able to reuse my ViewModels if I need similar functionality for a WinForms application?
  • Silverlight doesn't support all things WPF does - should I be able to reuse for Silverlight applications?
  • What if I want to make a Linux GUI for my application. Then I need the ViewModel to build in Mono - is this something I should strive for?
  • And so on..

So; should one write ViewModel classes with one specific View in mind, or think of reusability?


Solution

  • To answer your question, think about Single Responsibility Principle:

    "A class should have one, and only one, reason to change."

    I'd say, within reason, you typically don't want to reuse a ViewModel for multiple views. The main reason I'd argue for this, is because that would give your ViewModel more than one reason to change. In other words, it'd need to change if one or the other view changes, and in my opinion, that's two reasons to change. Where does it stop? I'd keep it simple in this case, and bind one ViewModel to the View.

    Another thing to think about with MVVM with WPF is Data Templating. It's much easier to accomplish if each ViewModel caters to one and only one view.