How can I use ViewModel classes for reuse?

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

  • Should I reuse my ViewModels if I need similar functionality for a WinForms application?
  • Silverlight does not support all WPF actions - should I reuse Silverlight applications?
  • What if I want to create a Linux GUI for my application. Then I need a ViewModel to build in Mono - should I aim for this?
  • And so on..

So, should you write ViewModel classes with one specific view in mind or think about reusability?

+7
wpf viewmodel mvvm reusability
source share
4 answers

To answer your question, consider the principle of shared responsibility:

"A class must have one and only one reason to change."

I would say, within reasonable limits, as a rule, you do not want to reuse the ViewModel for multiple views. The main reason I would approve this is because it will give your ViewModel several reasons to change. In other words, this should change if one or the other idea changes and, in my opinion, changes two reasons. Where does it stop? In this case, I would simplify this and bind one ViewModel to the view.

Another thing worth considering with MVVM with WPF is Data Templating. This is much simpler if each ViewModel is suitable for one and only one view.

+12
source share

In general, apply the YAGNI principle - you probably won't need it. If you cannot see these things as potentially happening, I will take the simplest approach so that your software works on the requirements that you currently have.

+3
source share

In my opinion, the main goal of MVVM is to exclude code that cannot be easily tested with unit tests . Since the view model can be checked by the module, but cannot be visible, this is achieved due to the fact that the view looks as deep as possible. Ideally, how this can be done using XAML, a view is fully declarative and only binds the data to a view model. Therefore, the "no code for" the mantra.

Reusing the view model in different user interface technologies is not really the goal of MVVM. If you try, you probably want to move the code specific to the user interface technology into the view again so that the view model is reused. This will be contrary to the main purpose of the audit.

If you really need to support different user interface technologies, then you can still divide the general logic of presentation models into a common "presentation" layer. I would not do this until I’m sure that this is necessary.

+2
source share

This is an old question, so I hesitate to add another answer. But all the answers posted so far have missed the point. The answer from MSDN is very clear: The ViewModel is very specifically designed to be shared by many views of various OSs, as shown in this figure:

enter image description here

Failure to do so will inevitably lead to redundant code.

0
source share

All Articles