I am working on a windows phone 8.1 universal app and want to find the best way of handling page navigations without having large amounts of logic in the code behind. I want to keep the code behind in my View as uncluttered as possible. What is the accepted MVVM way of navigating to a new page in response to a button click?
I currently have to send a RelayComnmand message from the ViewModel to the view with the details of the page to navigate to. This means that the code behind has to be wired up as follows:
public MainPage()
{
InitializeComponent();
Messenger.Default.Register<OpenArticleMessage>(this, (article) => ReceiveOpenArticleMessage(article));
...
}
private object ReceiveOpenArticleMessage(OpenArticleMessage article)
{
Frame.Navigate(typeof(ArticleView));
}
This just doesn't seem the best way although it does work. How can I do the page navigations directly from the ViewModel? I am using MVVM-Light in my project.
There is a new and simpler implementation here: https://marcominerva.wordpress.com/2014/10/10/navigationservice-in-mvvm-light-v5/
First we create the
NavigationService
andDialogService
(for the page navigation params):Then we create a
RelayCommand
andNavigationService
in yourViewModel
, like so:And finally, we can get the page navigation params like so:
But to read the arguments passed in page navigation in MVVM pattern, you can take a look here.
Ok, I have found an answer to this question. Took a bit of investigation but I eventually found the preferred MVVM-Light way of doing this. I don't take credit for this answer in anyway but just posting it here in case people are looking for an answer to this question.
Create an INavigationService interface as follows:
Create a NavigationService class as follows:
Now in the ViewModelLocator, set it up like this:
Next setup a navigation service for design time as follows:
My MainViewModel constructor is as follows:
Now you can simply use this to navigate in your viewmodel:
For more details on the original author Laurent Bugnion see this article and associated code. http://msdn.microsoft.com/en-us/magazine/jj651572.aspx
I agree with ricochete above, its simpler, though my direct implimentation messed up with my Design Data Binding in Blend.
I decided to create an a class that inherited from the NavigationService
Then in the ViewModelLocator I registerred it this way
My Design View Data Bindings worked again. If someone could explain why the design data wun't work in ricochete above, please do. Thank you!