Search code examples
c#wpfmvvmviewmodel

WPF MVVM communication between View Model


I am working on WPF MVVM application wherein I have 2 views View1 and View2 with their respective ViewModels. Now, I want on click of a button in View1 would close View1 and open View2 using ViewModel1. Also, I want to pass some data say a instance of person class to ViewModel2 when opening from ViewModel1 which would be used to display information in View2.

What is the best and possibly the simplest way to achieve this inside ViewModels only, I would want to avoid writing code for navigation in code behind.


Solution

  • How about using the Mediator pattern (for example see technical-recipes.com or John Smith) or weak events? Afaik several MVVM frameworks/libs (like PRISM, Caliburn.Micro, MVVMCross) already come with the infrastructure code for these. There are also separate libraries that are independent of any specific MVVM framework, like Appccelerate EventBroker which can help you achieve something along the lines of what you want.

    With events, however, I wonder whether you require some feedback on whether the event was "correctly" handled or not. There are ways to achieve this (altering the value of the event args, handling the events sync, after raising the event, checking the value of the event args), but they are not as concise as a method's return value or a method throwing an exception.

    EDIT: sorry I just realized that the second view/ViewModel is not open, yet. So my "solution" is not (that simply) applicable. You need to pass the instruction "up" in the view model tree, maybe even to the root, where you can instantiate and show the new view model (show in a new window or as a ContentControl in an existing view?)