简体   繁体   中英

MVVM Light Messages - Multiple ViewModel instances

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?

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");

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM