Should a view only snap to a ViewModel in mvvm?

Recently, I have to deal with the mvvm template in my new xamarin forms project. The code for the XAML page that has a bindingContext is a ViewModel. The hard part of my page is to use more than one ViewModel to complete my task. e.g. My HomePage should use the data in the contact ViewModel, user ViewModel, city ViewModel, ...

I searched on the Internet and people say that we should only use the viewmodel for a specific view. So, I am wondering if I should create a new view model that wraps all the above OR view model, I have to set a different bindingContext for each child view on this page.

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

+4
source share
4 answers

I would create a HomePageViewModel that encapsulates some other classes.

class HomePageViewModel
{
    UserViewModel user;
    ...
}

HomePageViewModel will become the DataContext HomePage, and the corresponding properties will be assigned to child layouts.

+1
source

, 1:1 - , , , . ; , , , - , "Hello World"! , 1:1 . .

, , , , . 4 " MVVM" ( ViewModel), , , , VM, VM .

+1

, , , bindingContext.

.

ViewModel , .

My HomePage ViewModel, ViewModel, city ViewModel,...

Child Views (UserControl, DataTemplate), ViewModel , ViewModels. ObservableCollections.

ViewModel , Contact (), , Contact Model.

0

, MVVM. , , . , , , , , . , , , , .

With WPF, using the view model as the parent binding context works well, even if your models are quite complex, because it allows you to navigate through classes. For example, you can snap to DataContext.User.Profile.FirstNameyour view model. Thus, you can have a view model that has a property for the user, contact, and address.

-1
source

Source: https://habr.com/ru/post/1611181/


All Articles