MVVM passes values ​​between view models

I am trying to solve the problem of passing a value from one ViewModel to another. Here is an example.

We have a Parent View and the corresponding ViewModel, in this view we select an element, and then want to create a new Child View (for editing selection details) that creates an instance of ViewModel in XAML. The problem occurs when I need to pass a value to the Child ViewModel constructor (this is the identifier of the data that should be retrieved from the database). I assume that the Parent ViewModel should interact with the Child ViewModel, but this cannot be done since the Child ViewModel is not created until the Child View does this in XAML, so we cannot use the Messenger (MVVM Light Toolkit) and just distribute this information from the Parent ModelView because Child ModelView could not subscribe (register for this type of message).

I do not want to break the MVVM pattern and cannot find a good solution for this. I appreciate all the help I can get.

+5
source share
2 answers

One of the main tenants of the MVVM template is that you should be able to execute your ViewModel code without a view so that unit test is your view logic. In words, ideally, you should be able to run your application in headless mode.

In your example, you indicate that ParentView creates a ChildView, which in turn creates a ChildViewModel (which you are trying to connect). Can this work in headless mode? It seems to me that you rely on your appearance to perform this navigation with your parent child.

If you change it in another way, create a ParentViewModel to create a ChildViewModel, you will no longer have a problem communicating between ViewModels. ParentView must "watch" (i.e., Change the property) for the new ChildViewModel to be created and accordingly create the ChildView.

More details:

  • ParentView instantiates ParentVM
  • The user interacts in such a way that a child is required.
  • ParentVM creates ChildVM by exposing it using the ChildVM property
  • ParentView handles the resulting PropertyChanged event, creating a ChildView, setting its DataContext for ChildVM.
+6
source

What if you use any framework? By this I mean MvvmLight, Caliburn Micro or Prism. Each infrastructure has a messaging infrastructure. You can use them to transfer state back and forth using the publish / subscribe methodology. For example, take a look at Prism. There are several Quickstarts that show an event model. You can also maintain a view controller to communicate between views.

Take a look at the Ward Bell Prism Explorer sample application. This article is from '09, but it is still relevant today. Especially see how it transfers an object of an object from a list view to a detailed view.

0
source

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


All Articles