Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM pass values between view models

I try to deal with problem of passing value from one ViewModel to another. Here is an example.

We have Parent View and its corresponding ViewModel, in that View we select item and then we want to create new Child View (to edit details of selection) which instantiates its ViewModel in XAML. Problem occurs when I need to pass value to the Child ViewModel constructor (it is Id of data that has to be fetched from database). I assume Parent's ViewModel has to communicate with Child's ViewModel - but it cannot be done since Child's ViewModel is not instantiated until Child's View do that in XAML, so we cannot use Messenger (MVVM Light Toolkit) and just propagate that info from Parent's ModelView because Child's ModelView has not been able to subscribe (register to that type of messages).

I do not want to break MVVM pattern, and cannot find any good solution for that. I appreciate for all help I can get.

like image 612
kkris1983 Avatar asked Jun 17 '11 23:06

kkris1983


1 Answers

One of the main tenants of the MVVM pattern is that you should be able to execute your ViewModel code without a View, in order to unit test your View logic. In othe words, ideally you should be able to execute your application in a 'headless' mode.

In your example you state that the ParentView creates a ChildView which in turn creates a ChildViewModel (which you are struggling to connect up). Can this work in headless mode? It seems to me that you are relying on your View to perform this Parent-Child navigation.

If you flip it the other way, have ParentViewModel create ChildViewModel, you no longer have a problem with communication between ViewModels. The ParentView needs to 'watch' (i.e. property change) for the new ChildViewModel being creates, and constructs the ChildView accordingly.

In more detail:

  1. ParentView instantiates ParentVM
  2. User interacts in such a way that the child is required
  3. ParentVM creates a ChildVM, exposing it via a ChildVM property
  4. ParentView handles the resultant PropertyChanged event, creating a ChildView, setting its DataContext to ChildVM.
like image 55
ColinE Avatar answered Nov 02 '22 04:11

ColinE