Simple WP7 Navigation with MVVM Light

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:

  1. // Option 1
  2. GotoProductCatalogCommand = new RelayCommand(
  3.     () => Navigate("/Views/ProductCatalogPage.xaml"));
  4. // Option 2, now without strings!
  5. GotoProductCatalogCommand = new RelayCommand(
  6.     () => 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:

  1. public void Navigate<T>()
  2. {
  3.     var UriFragment = String.Format(@"/Views/{0}.xaml"
  4.         , typeof(T).Name.Replace("ViewModel", ""));
  5.     Navigate(UriFragment);
  6. }
  7. public void Navigate(String uriFragment)
  8. {
  9.     var MyFrame = Application.Current.RootVisual as Frame;
  10.     MyFrame.Navigate(new Uri(uriFragment, UriKind.Relative));
  11. }
  12. public void GoBack()
  13. {
  14.     (Application.Current.RootVisual as Frame).GoBack();
  15. }

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.

Tags: , , , ,

Blog

About the author

I am a software developer working for Microsoft in Redmond, WA.  In addition, my wife and I own TTXOnline, what is likely the 3rd largest table tennis store in the US.

Month List

Page List