It is a common scenario to navigate to another URI on a button click. If you have MVVM fully wired up, this command in your View will likely connect to a method in your ViewModel. But the View is the one that can navigate via the NavigationService.
So, this means the ViewModel will need to tell the View to do so. One way to do this is by using the Messaging framework in MVVM Light toolkit.
For e.g. Let’s say your About button needs to go to to the About Uri. The following are the various steps involved.
1. View – Register the Message (to receive) in the source View.
Let’s say we want to look for a Uri and a token of “Navigate”. When it is received, we want to invoke the Navigation. This can be elegantly done with a delegate as follows
Messenger.Default.Register<Uri>(this, "Navigate",
(uri) => NavigationService.Navigate(uri));
2. ViewModel – Send this Message from a ViewModel, and MVVM Light will deliver it to the View
private void About(object param)
{
Uri uri = new Uri("/View/About.xaml", UriKind.Relative);
Messenger.Default.Send<Uri>(uri, "Navigate");
}
This ensures there is no tight coupling between the ViewModel and the View, as the pattern requires.
You can use this pattern even between 2 Views if you need.
July 26, 2011 at 6:42 am
i have to link a grid column with another XAML file. can you pls help me out with it. When i click on the Grid Column another xaml should open in same location. using WPF,MVVM.. pleaase help me out with it.
July 26, 2011 at 6:42 am
i have to link a grid column with another XAML file. can you pls help me out with it. When i click on the Grid Column another xaml should open in same location. using WPF,MVVM.. pleaase help me out with it….
August 4, 2011 at 5:16 pm
One possibility is to Navigate to the second xaml in the code-behind (yes, it is not pure MVVM because there is code in your view).
So, basically using Blend or Visual Studio double-click the event you want to trap or you might have to code it by hand.
And in the code-behind, put in your logic to navigate to the other View or use an event to do so (so send some event data here and consume the event elsewhere for Navigation)
This assumes that your grid supports the required event viz. the column-click.
Alternatively, if you can trap the command for the click in the ViewModel and have the Navigation logic there, then it’s more clean and conforms to MVVM.
February 22, 2012 at 3:16 am
swag bucks…
[...]Navigating between pages with MVVM Light « Techkn0w[...]…
February 22, 2012 at 5:06 pm
Did you find how to fix this?
February 22, 2012 at 5:05 pm
Can anyone share some sample(s)?
January 29, 2013 at 10:02 pm
“Navigating between pages with MVVM Light Techkn0w” was a splendid blog, can’t
help but wait to examine much more of ur articles. Time to spend
some time on the internet lol. Many thanks ,Crystle
March 4, 2013 at 3:39 pm
How do you suggest passing arguments to the new ViewModel of the “presented” page? Also in a MVVM manner. Thank you!