Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

6. MVVM > Communicating between different ViewModels

Communicating between different ViewModels

Communicating between different ViewModels Applies to Silverlight 3, 4, 5 and WP7 Often, you'll find yourself in need of sending messages between ViewModels. A very typical example would be: you've got a View with a ListBox, and once an item is selected, you want that item to be displayed in detail in another View. In other words, the standard master-detail requirement. How do you achieve this with MVVM? If you didn't follow the pattern, you could easily say: "well, I need to execute a method on ViewModel B when something happens in ViewModel A, so I'll keep a reference to ViewModel B in ViewModel A, so I can call the method when appropriate". This, of course, is tight coupling—your ViewModels aren't independent of each other anymore, and ViewModel A now knows that ViewModel B exists. What's more: if ViewModel B is removed, or heavily changed somehow, you'll need to update ViewModel A as well. This is, of course, not a good approach. In this recipe, we'll see how to tackle this problem. We will use MVVM Light's Messenger to communicate between ViewModels. Getting ready We're starting with the provided starter solution, which can be found in Chapter 6\Communicating_Between_ViewModels_Starter. The completed solution can be found in Chapter 6\Communicating_Between_ViewModels_Completed. How to do it... We're going to start from the provided starter solution, which includes two Views (PeopleView and PersonEditView) with their respective ViewModels, and we're going to ensure that once a person is selected in PeopleView, it is sent to PersonEditView and displayed on that View. We will use MVVM Light's Messenger for this. To achieve this, we'll complete the following steps: Open LocalStateContainer.cs and add the following: public static Messenger PersonMessenger = new Messenger(); Right-click on the Messages folder, select Add New class, and add a class named PersonSelectedMessage. Implement it as such: public class PersonSelectedMessage { public Person SelectedPerson { get; set; } public PersonSelectedMessage(Person person) { SelectedPerson = person; } } Open PersonViewModel.cs, and add the following code to the InstantiateCommands() method: SelectedPersonChangedCommand = new RelayCommand<Person>((p) => SelectedPersonChangedExecution(p), (p) => true); Add the following method: private void SelectedPersonChangedExecution(Person selectedPerson) { // send a message to notify anyone who's registered that the selection // has changed LocalStateContainer.PersonMessenger.Send<PersonSelectedMessage>(new PersonSelectedMessage(selectedPerson)); } Open PersonEditViewModel.cs, and add the following method: private void InstantiateMessenger() { LocalStateContainer.PersonMessenger.Register<PersonSelectedMessage>(this, (msg) => PersonSelectedMessageReceived(msg)); } Call this method from the PersonEditViewModel constructor.Add the following method: private void PersonSelectedMessageReceived (PersonSelectedMessage msg) { CurrentPerson = msg.SelectedPerson; } You can now build and run your application. How it works... The Messenger is a classic messaging service provided by MVVM Light. It works via subscription/broadcasting principles. If you want to receive a message of a certain type, you have to subscribe yourself to receive that type of message through the messenger. Once a message of the type you've subscribed to is broadcasted through that same messenger, you will receive it and can execute the necessary code. In our example, the Messenger mediates between PersonViewModel and PersonEditViewModel. They can communicate with each other, without knowing each other's existence. Like this, our loose coupling is kept in place. In the first steps of our example, we're instantiating a Messenger: PersonMessenger. This instance will be used to send messages between PersonViewModel and PersonEditViewModel. We want to pass a Person instance from PersonViewModel to PersonEditViewModel, so we start out by creating a PersonSelectedMessage, which can be instantiated by passing in a Person instance. The PersonEditViewModel must be able to receive a message of this type, and execute the necessary code to set its CurrentPerson property to the Person instance it received. That's what the code in steps 5 and 6 is for: we're using our PersonMessenger instance, and telling it that it should register this ViewModel to receive messages of type PersonSelectedMessage. When such a message is received, the PersonSelectedMessageReceived method is executed. Only one thing is left now—sending the actual message. We're handling the SelectionChanged event of the ListBox on PeopleView through commanding and, in the handler, we're creating a new message of type PersonSelectedMessage, instantiating it by passing in the currently selected Person. This is then broadcasted via PersonMessenger, and will be received by our PersonEditViewModel, as this ViewModel is registered to receive messages of that type from our PersonMessenger. There's more... The Messenger we've used in this case was an instance we created to communicate between two specific ViewModels: PersonViewModel and PersonEditViewModel. This is perfect if you're sure certain messages should only be sent between a specific set of ViewModel instances (for example, if your application consists of a Reporting module and a User Management module, messages concerning the one or the other will typically only be sent between ViewModels belonging to that specific module), you would use a self-created Messenger instance. You've also got the possibility to send application-wide messages, as every ViewModel in MVVM Light has access to the default Messenger. Have a look at the recipe Leveraging a messenger to wrap application-wide messages, for an implementation of this. See also For more information on MVVM, have a look at the other recipes in this chapter.

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint