Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should ViewModels ever be reused by different Views? If so, when?

Tags:

mvvm

wpf

From what I have read, it seems to be considered a best practice in MVVM for each View to have its own corresponding ViewModel, which makes sense, since the ViewModel is supposed to be the model of the View. Generally, reuse of ViewModels by different Views seems to be discouraged. Is this always the case? If not, what are the general guidelines for determining whether or not a ViewModel should be reused in this manner?

One situation I can think of where it might be satisfactory to reuse a ViewModel with a different View is when two Views make use of the exact same data from the Model and the Views themselves just represent the data differently. If the Views can handle representing the same data in different ways themselves, one ViewModel might be able to serve each View effectively.

like image 439
foven Avatar asked Jan 17 '11 05:01

foven


1 Answers

The reason we have rules is so that you think before breaking them.

That is: there's nothing wrong with using the same ViewModel for two similar views. You do need to be very careful that your two views don't diverge, leaving you with a viewmodel that's attempting to do two different things.

This is why the recommendation is to have one viewmodel per view. Even though this might lead to duplication, it'll make maintaining the views easier in the long run.

As for the duplication, there's nothing wrong with viewmodel classes that have a shared base class.

like image 121
Roger Lipscombe Avatar answered Oct 21 '22 13:10

Roger Lipscombe