1
votes

HI, I try to understant how to send a message directly to a speciciel Target. I got a small SL projet and and a dunmmy class named class1. I register in the class constructor and listenig for all string type message.

public class Class1
{
    public Class1()
    {
        Messenger.Defaut.Register<String>(this, f => { TraiteMessage(f); });
    }

    public void TraiteMessage(string sMessage)
    {
        MessageBox.Show("Class1:" + sMessage);
    }
}

Now I send the message like this:

Messenger.Defaut.Send<String, Class1>("test message");

The message do not reach the target. When I look into the internal source code of the MVVM light i can see that the test are done like: item.Action.Target.GetType() == messageTargetType but in fact the messageTargetType are set to: MyProejet.Class1 but the item.Action.Target.GetType() return something like: {System.Collections.Generic.Dictionary2System.Type,System.Collections.Generic.List1[SLDuninLib.Messages.Avise+WeakActionAndToken]]} System.Type {System.RuntimeType}

what do i do wrong? Thanks for your help

2

2 Answers

0
votes

Is an instance of Class1 created anywhere? If not, then it never registers to receive any messages.

You can easily test this by putting a breakpoint on the line of code that registers to receive the message in the Class1 constructor.

I tested your code and it works when I have the message registration in another view model, but this is because any view models in the ViewModelLocator are created as soon as the App.xaml is loaded.

0
votes

When TTarget defined, the message is awared by its type, not instance. So, your code did not work (as you experienced) because you sent a message with Class1 type but receipient you register was String type, not Class1 type.

So, in this case, several solutions can be considered.

  • Make Class1 static and handle received message as below:

Messenger.Defaut.Register<Class1>(this, msg => { Class1.TraiteMessage(msg); });

  • Or, send message in string type same as registered type.

Messenger.Defaut.Send<String, String>("test message");

  • Or, define a small struct which contains variables you want to transfer between them as below.

public struct SearchTerm { public string Category; public string Keyword; }

send as below:

Messenger.Default.Send(new SearchTerm{Category = "Q",Keyword = "something"}));

and consume in Class1 as below:

Messenger.Default.Register<SearchTerm>(this,msg => {TraiteMessage(msg.Keyword);});

For me, the last solution is prefered.

Cheers