1

I'm sure this has been asked before but I can't get a proper answer.

Herewith the scenario:

I have a grid with two Graphs on each row. Clicking on something on Graph1, sends a Message using from Code Behind of Graph1 :

Messenger.Default.Send<MyCustomMessageType>(message);

then, on my ViewModel for Graph 2, I register in the constructor:

Messenger.Default.Register<MyCustomMessageType>(this, (message) => UpdateDataContext(message));

The problem is that the Send, now sends it to ALL Instances of the ViewModel of that Type (Which does make sense).

How do I stop this from happening?

D.Rosado
  • 5,634
  • 3
  • 36
  • 56
Fox
  • 891
  • 3
  • 9
  • 30
  • you can use token which is used as a key to your message. – loop Jul 04 '13 at 13:41
  • Hi there. I've read about the tokens.. but how to use them? How do I know in my receiving viewmodel which token to use? My ViewModel is not immediately constructed – Fox Jul 04 '13 at 13:42

3 Answers3

3

Send a token to specify the receivers

void Register<TMessage>(object recipient, object token, Action<TMessage> action);
void Send<TMessage>(TMessage message, object token);

Example:

MessengerInstance.Register<Foo>(this, "thespecialone", theFoo=> FunctionFoo(theFoo));
MessengerInstance.Send<Foo>(message, "thespecialone");
D.Rosado
  • 5,634
  • 3
  • 36
  • 56
0

Thanks all for the answers. The message was not my problem. The problem was that I was using the ViewModelLocator when I shouldn't have. Because Each row needs its own ViewModel, I got rid of using the ViewModelLocator and just Instantiated the ViewModel in the Onload of the control and setting that as the Datacontext. Thanks for the advice though.

Fox
  • 891
  • 3
  • 9
  • 30
0

First of all, you can register viewmodels for messages outside of constructor, preferably in ioc. Second, dont use Default (singleton), manage Messanger instances as you need for particular group of viewmodels. PS one of the greatest benefits of this approach (besides obviously useful granularity and decoupling) is support for proxies.