1
votes

Hey guys, I'm building a project using Silverlight and the MVVM pattern, what I need to do is, navigate to a page which has a view model in it as the LayoutRoot's DataContext, I need to pass an object to that view model for editing but since it's not constructed yet, I won't be able to use the MVVM Light Messenger class, because in order to send a message you need to register that specified type first.

So is it possible to send a message before the view model class is constructed and when it's constructed I could be able to get the message?

2
i don't think you can send message to a object never created.. i think you should try using some Session Dictionary and set the value from one ViewModel and then read the value once you Navigated on another View.Shoaib Shaikh
You're right that you cannot send a message to something not created yet, so let's turn the question around. How can my newly instantiated object receive messages previously intended for it? A sort of message voice-mail it can check on creation, if you will. See my answer below for this sort of solution.Sean Hanley
That's exactly what I'm looking for, so I need to check it out.Peymankh

2 Answers

0
votes

I've not tried it myself, but this guy seems to have a pretty good solution to this common problem. You can view the source for it (without having to download the entire contrib project) here by looking under the WP7Contrib.Messaging folder for the single cs file that implements it. The project as a whole is intended for mobile applications (specifically WP7) but this custom Messenger implementation is really independent of that.

Basically, he makes a special Messenger implementation that "re-tweets" the last message for a given type signature every time someone new registers to listen for them. This way, the first VM can send its message, the second VM will get created (probably by your IoC container or whatever) and register to listen and immediately get the message that was sent before it existed.

Of course, this can have some problems with race-conditions. It relies on no other messages being sent for a given signature until the intended recipient has had a chance to receive it. In practice, though, I imagine this isn't too much of an issue. Particularly if you make good use of the target and sender parts of messages.

0
votes

All you view models should be created before the root visual is set.

Set breakpoints

Set breakpoints

Set breakpoint at MainViewModel()

Set breakpoint at Sub3View()

MainViewModel() is hit first.

MainVieModel() is hit first

Sub3ViewModel() is hit, listener registered.

Sub3ViewModel() is hit, listener registered

RootVisual is set.

RootVisual is set