Using MVVM Light Messenger to Transfer Values ​​Between a View Model

Can anyone be so kind as to explain to me MVVM Light Messenger? I read a post on StackOverflow here: MVVM passes values ​​between view models , trying to get this. The documentation for MVVM Light is not very good at this point, so I'm completely unsure where to go.

Let's say I have two models ViewModels and ViewModelLocator. I want to be able to pass parameters between all three without problems. How will I do this with the messenger? Is it capable?

Edit: Here is my new implementation. At the moment, it looks like MessengerInstance does not require a token. I'm terribly confused.

In the first ViewModel:

MessengerInstance.Send<XDocument>(SelectedDocument); 

And in the second:

 MessengerInstance.Register<XDocument>(this, xdoc => CopySettings(xdoc)); 

It may be completely wrong. I did not have the opportunity to verify this, but the visual studio is less angry with me when I do this. Also, MessengerInstance is registered before the message is sent.

+6
source share
1 answer

Let's say I have two models ViewModels and ViewModelLocator. I want to be able to pass parameters between all three without problems. How will I do this with the messenger? Is it capable?

What exactly, yes.

Send a message:

 MessengerInstance.Send(payload, token); 

To receive a message:

 MessengerInstance.Register<PayloadType>( this, token, payload => SomeAction(payload)); 

There are many overloads, therefore, not knowing exactly what you are trying to do through the messenger, I will not go into all of them, but the above should cover a simple case when you want to send and receive a message with a payload.

Note that a token can really be anything that identifies a message. Although a string is often used for this, I prefer to use an enumeration because it is a little safer and allows intellisense, "find usages", etc.

For instance:

 public enum MessengerToken { BrushChanged, WidthChanged, HeightChanged } 

Then your transfer / receipt will look something like this:

 // sending view model MessengerInstance.Send(Brushes.Red, MessengerToken.BrushChanged); // receiving view model // put this line in the constructor MessengerInstance.Register<Brush>(this, token, brush => ChangeColor(brush)); public void ChangeColor(Brush brush) { Brush = brush; } 

[EDIT] The devuxer comment URL below is changed to: http://blog.galasoft.ch/posts/2009/09/mvvm-light-toolkit-messenger-v2/

+13
source

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


All Articles