views:

84

answers:

2

Hello, I am prototyping a windows phone 7 application in silverlight. I am trying to use MVVM pattern in my application. I have the following situation:

I navigate from one view1 (page) to another view2 (page) using NavigationService.Navigate("uri of next page") method [Please note NavigationService is a sealed class, so cannot be overriden]. Basically, View2 is not initialized until View1 navigate to it.

I bound View1 and View2 to same ViewModel. So, app is launched - launches View1 and ViewModel and gets a deserialized object. On getting this deserialized object ViewModel sends a message to View1 to navigate to View2 (which is also bound to same type of ViewModel but another instance).

So, my questions is: How can I pass the Object from one View1 to View2 when View2 is not controlled/created by View1 (View1 just navigates to View2).

I hope it is clear. I will continue to monitor to edit it per your comments. Thanks

EDIT: Essentially, I would like one view to get data that I can bind to next view. I would like to navigate to next view based on the type of object I get from http request. This way, if there is any error, I will stay on present view (and not move to next view).

+2  A: 

I would definitely check out Laurent Bugnion's MVVM Light toolkit. I've done what you've described here using his framework and it works like a champ! He's got some walkthroughs on his blog as well as a video on Channel 9 to help you get started. I've also got a blog series on WP7 that features the MVVM Light toolkit and a new post that I'm almost ready to publish doing exactly what you're asking about.

Basically what you'll need to look at is the Messaging infrastructure that MVVM Light provides. With this framework, your "source" ViewModel will put a message on the bus that the "target" ViewModel listens for. Check out the links and let us know if that works for you!

/ck

Chris Koenig
Thanks Chris and Andréas Saudemont. For some reason, SO was not not showing any option to comment. I looked at this ViewModelLocator, I think it is pretty cool.
curiousone
A: 

If you can somehow reference the shared object by a string value, then you can pass this string value as a parameter in the URL of the View2 page and retrieve it using NavigationContext.QueryString.

So when navigating from View1:

string objectId = GetObjectId(sharedObject);
Uri uri = new Uri(
    string.Format("/View2.xaml?objectId={0}", objectId), UriKind.Relative);
NavigationService.Navigate(uri);

And in the OnNavigatedTo() method of View2:

object sharedObject = null;
if (NavigationContext.QueryString.Contains("objectId"))
{
    sharedObject = GetObjectFromId(NavigationContext.QueryString["objectId"]);
}
if (sharedObject != null)
{
    // do some stuff with sharedObject
}

Now all you have to do is implement the GetObjectId() and GetObjectFromId() methods. :)

Andréas Saudemont