1

I have a scenario where there are two pages to display orders in progress and delivered orders. The pages have almost identical binding and commands, so making separate ViewModels would result in code duplication

I was recommended to use the same ViewModel for both pages since the they would represent the same model, only order statuses would differ. The data comes from different endpoints, so I have two service methods. I don't like the idea of making one ViewModel for both pages, because this would make me to tell the ViewModel that it should get the Orders from one of the service methods when initializing the ViewModel.

The solution that I've thought of is to have OrdersViewModel as a base class, where all the common members are there, and create two derived classed called OrdersInProgressViewModel and DeliveredOrdersViewModel.

My every ViewModel has a method called InitializeAsync, if I decide to go with the first approach and have single ViewModel for both pages, I would probably have to pass down the status as navigation data to InitializeAsync and decide there which service method use to fetch orders.

With the second approach, I could have two separate ViewModels and in their InitializeAsync call the corresponding service method.

Which approach would adhere to MVVM more?

I also need to keep in mind, that more page specific behavior might be requested (another argument against single ViewModel for both pages)

Reed
  • 1,161
  • 13
  • 25
  • Possible duplicate of [MVVM Inheritance With View Models](https://stackoverflow.com/questions/977652/mvvm-inheritance-with-view-models) – markorial Jan 20 '19 at 16:59
  • 1
    There is nothing wrong with creating BaseViewModel for viemodels with similar functionality. Responsibility of ViewModel is to separate logic from the view. – FCin Jan 20 '19 at 16:59

1 Answers1

0

I would suggest you to use the second approach you've described. Using a base viewmodel class and then implement derived classes.

EDIT

The answer to a similar question, in fact, is very similar to what I mean.

Generally I would recommend you not to have inheritance between different ViewModel classes, but instead having them inherit directly from a common abstract base class. This is to avoid introducing unnecessary complexity by polluting the ViewModel classes' interfaces with members that come from higher up in the hierarchy, but are not fully cohesive to the class's main purpose. The coupling that comes with inheritance will also likely make it hard to change a ViewModel class without affecting any of its derived classes.

Richard
  • 128
  • 2
  • 3
  • 10