nemesis
nemesis

Reputation: 263

is it bad to have viewmodels within viewmodels?

So I've check this post and a couple of others that discuss similar situations, but still haven't found the best solution to the problem I'm trying to solve.

In my mvvm application each view has one viewmodel. I want to make the viewmodels as flat as possible, but it doesn't seem to be practical when it comes to binding with observable collections. For example, If I have a page that displays a client's profile information, and one of the fields is a group of checkboxs for active subscriptions. I would have a viewmodel that looks like this:

public class ClientViewModel
{
    public class SubscriptionViewModel
    {
        public SubscriptionModel Subscription {get;set;}
        public bool IsChecked {get;set;}
    }

    public string Name {get;set;}
    public string Email {get;set;}
    ...
    public ObservableCollection<SubscriptionViewModel> Subscriptions {get;set;}
}

Because of the extra IsChecked property that is not part of SubscriptionModel, I have to create a separate SubscriptionViewModel and nest it inside the client. What would be a better alternative way to do this so that I don't have to end up with viewmodels inside viewmodels?

Upvotes: 12

Views: 8460

Answers (1)

Martin Moser
Martin Moser

Reputation: 6267

For me it's perfectly fine to compose VM out of several others. I'm doing this quite a lot. Sometimes due to the need to re-use parts, sometimes just to have a better readability in the code. Every VM has still a corresponding view. So there is a view for the "inner-viewmodel" as well as a view for the "composed-viewmodel".

I would not use nested public classes though. I'm treating them as "first-class-citizen".

The scenario I've recently had, was a small product information display on a customer page as well as the invoice page. So I decided to create a ProductOverviewViewModel as well as a ProductionOverviewView, and both are used within the customer and invoice views/viewmodels.

Upvotes: 10

Related Questions