topcbl
topcbl

Reputation: 849

Should a View only bind to a ViewModel in mvvm?

Recently, I have to deal with mvvm pattern in my new xamarin forms project. The Page code on XAML which have bindingContext is ViewModel. The hard part is my Page need to use more than one ViewModel to accomplish my task. e.g. My HomePage need to use data in contact ViewModel, user ViewModel, city ViewModel, ...

I've searched on the internet and people say that we should use only a viewmodel for a specified view. So, I wonder if i should create a new viewmodel which wrap all of above viewmodel OR i should set different bindingContext for each of child view in that page.

Anyone experienced in this case and which one is the best solution.

Upvotes: 3

Views: 703

Answers (3)

Mark Feldman
Mark Feldman

Reputation: 16148

The idea that a 1:1 relationship is somehow antithetical to a view model hierarchy is misguided, to say the least. The view model is a logical representation of the view; implementing a hierarchy of view models thus not only adheres to the architecture it's practically a requirement for anything more complicated than a "Hello World" app! Any real-world application will have a complex visual hierarchy of views, so by definition the 1:1 relationship mandates a similar hierarchy within the view model. This is just common sense.

But don't just take my word for it, take a look at any code written by the experts on this topic and you'll see they all do the same thing. A good starting point is Chapter 4 of Josh Smith's "Advanced MVVM" (ViewModel Architecture Overview) in which even his simple application contains a high-level VM encapsulating both the game and game-over VMs, and with the game VM itself consisting of separate VMs for the field and individual game elements.

Upvotes: 1

Aaron Hawkins
Aaron Hawkins

Reputation: 2691

Yes, a view should only bind to a single View Model in MVVM. I certainly wouldn't derive from or wrap other view models. The main idea here is to use the models that are required by your view in a view model that is specific to your view so you can see easily see exactly what this view requires. It also allows you to simplify your code as you will only have the code needed to make the view work, nothing more, nothing less.

With WPF, using the view model as the parent binding context works well even if your models are fairly complicated because it allows for class navigation. For instance, you can bind to DataContext.User.Profile.FirstName in your view model. So, you could have a view model that has a property for user, contact, and address.

Upvotes: -2

Adil
Adil

Reputation: 3268

I would have created HomePageViewModel which encapsulates some other classes.

class HomePageViewModel
{
    UserViewModel user;
    ...
}

HomePageViewModel will become DataContext of HomePage and the child layouts will be assigned respective properties.

Upvotes: 2

Related Questions