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:
public interface INavigationService
{
void Navigate(Type sourcePageType);
void Navigate(Type sourcePageType, object parameter);
void GoBack();
}
Create a NavigationService class as follows:
public class NavigationService : INavigationService
{
public void Navigate(Type sourcePageType)
{
((Frame)Window.Current.Content).Navigate(sourcePageType);
}
public void Navigate(Type sourcePageType, object parameter)
{
((Frame)Window.Current.Content).Navigate(sourcePageType, parameter);
}
public void GoBack()
{
((Frame)Window.Current.Content).GoBack();
}
}
Now in the ViewModelLocator, set it up like this:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<INavigationService, Design.DesignNavigationService>();
}
else
{
SimpleIoc.Default.Register<INavigationService>(() => new NavigationService());
}
SimpleIoc.Default.Register<MainViewModel>();
}
Next setup a navigation service for design time as follows:
public class DesignNavigationService : INavigationService
{
// This class doesn't perform navigation, in order
// to avoid issues in the designer at design time.
public void Navigate(Type sourcePageType)
{
}
public void Navigate(Type sourcePageType, object parameter)
{
}
public void GoBack()
{
}
}
My MainViewModel constructor is as follows:
public MainViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
...
Now you can simply use this to navigate in your viewmodel:
_navigationService.Navigate(typeof(WelcomeView));
For more details on the original author Laurent Bugnion see this article and associated code.
http://msdn.microsoft.com/en-us/magazine/jj651572.aspx
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…