这是我实现的导航服务。不会声称它是完美的,但它对我有用。这也早于 MVVM Light 5 中的内置导航服务,但您仍然可以使用它,或者它的一部分。
使用
在 ViewModelLocator 中注册它
SimpleIoc.Default.Register<INavigationService, NavigationService>();
然后通过构造函数将其注入到您的视图模型中。使用NavigateTo() 导航到其他页面;后退按钮按下处理程序仅在没有更多历史记录时退出应用程序,否则导航到上一页。
public interface INavigationService
{
void NavigateTo(Type pageType, object parameter = null);
void NavigateTo(string pageName, object parameter = null);
void GoBack();
}
.
public class NavigationService : INavigationService
{
#region Public
/// <summary>
/// Navigates to a specified page.
/// </summary>
public void NavigateTo(string pageName, object parameter = null)
{
Type pageType = Type.GetType(string.Format("SendToSync.{0}", pageName));
if (pageType == null)
throw new Exception(string.Format("Unknown page type '{0}'", pageName));
NavigateTo(pageType, parameter);
}
/// <summary>
/// Navigates to a specified page.
/// </summary>
public void NavigateTo(Type pageType, object parameter = null)
{
var content = Window.Current.Content;
var frame = content as Frame;
if (frame != null)
{
var previousPageType = frame.Content.GetType();
if (previousPageType != pageType)
NavigationHistory.Add(previousPageType);
//await frame.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => frame.Navigate(pageType));
frame.Navigate(pageType, parameter);
}
Window.Current.Activate();
}
/// <summary>
/// Goes back.
/// </summary>
public void GoBack()
{
var content = Window.Current.Content;
var frame = content as Frame;
if (frame != null)
{
var currentPageType = frame.Content.GetType();
// remove the previous page from the history
var previousPageType = NavigationHistory.Last();
NavigationHistory.Remove(previousPageType);
// navigate back
frame.Navigate(previousPageType, null);
}
}
#endregion
#region Private
/// <summary>
/// The navigation history.
/// </summary>
private List<Type> NavigationHistory { get; set; }
#endregion
#region Initialization
public NavigationService()
{
NavigationHistory = new List<Type>();
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
/// <summary>
/// Called when the back button is pressed; either navigates to the previous page or exits the application.
/// </summary>
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if (NavigationHistory.Count == 0)
{
e.Handled = false;
}
else
{
e.Handled = true;
GoBack();
}
}
#endregion
}
编辑:这是我的 ViewModelLocator 的一部分
在构造函数中:
SimpleIoc.Default.Register<MainViewModel>();
以及附带的属性:
public MainViewModel MainViewModel
{
get { return ServiceLocator.Current.GetInstance<MainViewModel>(); }
}
这将始终返回 MainViewModel 的相同单个实例(并且视图模型数据将保持不变)。