3
votes

I want to make a layout that is composed of multiple views and each view has it's own viewmodel.

I also want to implement a ViewModel-first approach. So I want to put some containers in my view that their datacontext is bound to corresponding viewmodel property of the container viewmodel. Then content of the container will load based on a data template written for the bound viewmodel type.

public class CompositVm
{
        public FirstPartVm FirstPartVm { get; set; }
        public SecondPartVm SecondPartVm { get; set; }
}

I want to know weather nesting viewmodels is a good practice and is it compatible with MVVM design pattern?

1
could you give a rough example ? - Noctis
I don't see any issue from the mvvm point of view - nkoniishvt

1 Answers

4
votes

Yes. There is nothing wrong in that. It is the best practice to do in MVVM approach.

Say you have a main layout view MainLayout which is bound to MainLayoutViewModel. Inside the MainLayout view you may have 2 child views maybe separating the main view into 2 rows or 2 columns say ChildLayout1 bound to ChildLayout1ViewModel and ChildLayout2 bound to ChildLayout2ViewModel.

For this you could create instances of the Child view models’ in the MainLayoutViewModel

ChildLayout1ViewModel ChildLayout1ViewModelInstance = new ChildLayout1ViewModel();
ChildLayout2ViewModel ChildLayout2ViewModelInstance = new ChildLayout2ViewModel();

You could set the DataContext of the views in the MainLayout.xaml itself. This is very useful when we are dealing with views having very large data bindings. It is easy to separate them and handle the events and data accordingly.

So it is definitely the best thing to do while following MVVM model.