Prism Navigation – ViewModel first

Navigating to view using prism navigation service is straight forward and there are lot of examples on web around this.With MVVM i always found ViewModel first approach as best because of lot of reasons, some of them are

  • With MVVM, ViewModels is your application
  • No threading issues as you will always create view models which can be created on any thread.
  • More responsive , you are not dealing with dispatcher context to create views and let WPF system decide when to create views.
  • No Memory leaks, The life cycle of views is controlled by WPF system in most efficient way
  • More testable application, Since you app lives in view models and they don’t have UI beasts,
  • And lot more..

This post cover a small trick to implement the ViewModel first navigation using Prism 5.0 for WPF.

1. What ever IoC you are using (the code is based on StructuralMap) expose the RegisterForNavigation<T> method and from module initialization, register interface of viewModels participating in navigation process. The RegisterForNavigation<T> will look like

public static void RegisterTypeForNavigation<T>(this ConfigurationExpression reg)
{
reg.For<object>().Use(() => ServiceLocator.Current.GetInstance(typeof(T)))
.Named(typeof(T).FullName);
}

And some where in module initialization you call this method

configurationExpression
.RegisterTypeForNavigation<ICustomerDetailViewModel>();

And to navigate to this view model just use

var parameters = new NavigationParameters { { "Activity", SelectedActivity }, { "ColumnName", columnName } };
var uri = new Uri(typeof(ICustomerDetailViewModel).FullName, UriKind.RelativeOrAbsolute);
regionManager.RequestNavigate(ShellRegions.Workspace, uri, parameters);

And obviously some where in you data template definition there should a (DataTemplate) mapping which WPF uses to swap the view model with corresponding view (and set data context too)..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s