MVVM pass values between view models

后端 未结 2 786
傲寒
傲寒 2021-01-05 06:49

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 s

相关标签:
2条回答
  • 2021-01-05 07:39

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

    Take a look at Ward Bell's Prism Explorer sample app. This is an article from '09 however it's still relevant today. Especially see how he passes an entity object from a list view to a child detail view.

    0 讨论(0)
  • 2021-01-05 07:43

    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.
    0 讨论(0)
提交回复
热议问题