One framework to rule us all…
Windows 8, Windows RT

Windows Store App: Ways to send parameters when navigating between ViewModels

This is a quick reference for those starting on Windows Store Application development. If you are using Caliburn.Micro (if not, you probably should), you’re certain to require passing data between ViewModels/Screens. I’ll expose two ways you can go for to achieve this. Assuming you have a local reference/dependency for Caliburn’s INavigationService, first approach is to call the NavigateToViewModel method (the example is in the context of a ICommand.Execute()-type call):

The method accepts one parameter, and that’s where you should send your data. In the destination ViewModel, on the other hand, in order to access the data, you need to specify a property named “Parameter”, with the same type as data you are passing. According to the previous example, we would need to define a string property:

And that’s it. Make sure your init logic is done on PropertyChange() or in the setter (not good design though).

Secondly, and my preferred way, is to set a delegate. In the Navigation Service call we would invoke UriFor() instead, and define a initialization expression:

This approach, although it requires a few characters more, is more verbose and strongly typed, and in the destination View Model it gives us total liberty to define the properties we see fit. One last think though: these parameters are automatically injected in the properties of your view model, but they still are strings: you can use the WithParam() method to pass to the destination View Model plain values, like strings, but you can’t use it to pass complex objects. To do so, you will need the first solution.

Short and sweet. Enjoy!

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Leave a Reply