by jasonrshaver
31. January 2012 12:42
So, you enjoy the MVVM pattern for your Silverlight or Windows Phone 7 application, but you can't figure out how to perform your navigation from your ViewModel? Here is a guide that allows you to do this from your ViewModel:
- // Option 1
- GotoProductCatalogCommand = new RelayCommand(
- () => Navigate("/Views/ProductCatalogPage.xaml"));
- // Option 2, now without strings!
- GotoProductCatalogCommand = new RelayCommand(
- () => Navigate<ProductCatalogPageViewModel>());
The first option allows you to give a URI to navigate to, just like you would expect, but option two allows your application to navigate based on convention. Never miss-type a URI again!
All you have to do is add the following to your ViewModel base class or MVVM Light’s ViewModelBase:
- public void Navigate<T>()
- {
- var UriFragment = String.Format(@"/Views/{0}.xaml"
- , typeof(T).Name.Replace("ViewModel", ""));
- Navigate(UriFragment);
- }
- public void Navigate(String uriFragment)
- {
- var MyFrame = Application.Current.RootVisual as Frame;
- MyFrame.Navigate(new Uri(uriFragment, UriKind.Relative));
- }
- public void GoBack()
- {
- (Application.Current.RootVisual as Frame).GoBack();
- }
Notice that my ‘convention’ for Views is to basically take the type name of your ViewModel, remove the string “ViewModel” and look up the file in the “/Views” directory. Obviously you can move to a more comprehensive convention as your needs require.