[MVVM Light] the use of Messager, mvvmlightmessager
I. Preface
In the MVVM programming mode, sometimes we encounter a very embarrassing situation:
Multiple xaml. cs reuse a ViewModel. What should we do when ViewModel wants to pass a specific message to a certain xaml. cs?
Or What should I do if one. cs is not convenient to use in another. cs file, but I really want to pass the message to that. cs?
Today we will talk about the Messager class in MVVM Light, which inherits from the IMessager interface.
Ii. Usage
Sending pageMedium:
Messenger. default. send <TMessage> (TMessage message); // The first method is Messenger. default. send <TMessage> (TMessage message, object token); // The second method is Messenger. default. send <TMessage, TTarget> (TMessage message); // method 3
Generally, the first one is enough: (the T in it can be of various types)
Here, this is the uploaded page. You can decide to upload the specific part of the current page: this. your_property or this. your_method.
Messenger.Default.Send<GenericMessage<T>>(new GenericMessage<T>(this, value));
Receiving pageMedium:
Messenger.Default.Register<GenericMessage<T>>(this, Your_Action);private void Your_Action(GenericMessage<T> msg){ // do with msg}
Msg will contain the value of the sending page, so that I can process the msg.
Iii. Various situations
When receiving a sending page and a page: An example of the second part
When receiving multiple sending pages on a single sending page: Filter msg on the respective receiving pages to obtain the messages required on the receiving page.
When receiving multiple sending pages: T can be set for each sending page, that is, the message type, as long as the receiving page receives the desired Send page with the corresponding type during Register.
Iv. Summary
In MVVM, these Messager classes are used less, which makes the code unreadable and the code layout of the program unclear. Because when you use Messager. Default. Send on a page, it is inconvenient for others to find the Register where your code is. Unlike the two pages, F12 can be quickly tracked by referencing them. You can only consider the Messager class when you really cannot.