网上已经有很多方法了,比如通过Messenger来实现等等。这里我只讲述一种我比较喜欢的方法,因为它很方便
首先定义一个ViewModel基类,将所有ViewModel子类继承这个基类。在基类中定义
protected bool RemoveBackEntry { get; set; } public NavigationService NavigationService { get; set; } public NavigationContext NavigationContext { get; set; } public virtual void OnNavigatedTo(NavigationEventArgs e) { } public virtual void OnNavigatingFrom(NavigatingCancelEventArgs e) { } public virtual void OnNavigatedFrom(NavigationEventArgs e) { if (RemoveBackEntry) { RemoveBackEntry = false; NavigationService.RemoveBackEntry(); } }
因为在MVVM中,我们将会在所有页面上都加上DataContext,只要拿到DataContext就能拿到ViewModel,所以我们就可以定义子类WPhoneApplicationPage来继承PhoneApplicationPage这个类。
public class WPhoneApplicationPage : PhoneApplicationPage { protected WPhoneApplicationPage() { Loaded += PageBaseLoaded; } private void PageBaseLoaded(object sender, RoutedEventArgs e) { var viewModel = DataContext as ViewModel.ViewModel; if (viewModel != null) { viewModel.NavigationService = NavigationService; } } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); var viewModel = DataContext as ViewModel.ViewModel; if (viewModel != null) { viewModel.NavigationContext = NavigationContext; viewModel.OnNavigatedTo(e); } } protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { base.OnNavigatingFrom(e); var viewModel = DataContext as ViewModel.ViewModel; if (viewModel != null) { viewModel.NavigationContext = NavigationContext; viewModel.OnNavigatingFrom(e); } } protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); var viewModel = DataContext as ViewModel.ViewModel; if (viewModel != null) { viewModel.NavigationContext = NavigationContext; viewModel.OnNavigatedFrom(e); } } }
这样在ViewModel中就可以调用NavigationService了。
此外,还需要修改View,让View继承WPhoneApplicationPage
xaml布局文件中
1 <phone:WPhoneApplicationPage //修改PhoneApplicationPage 为 WPhoneApplicationPage 2 xmlns:phone="clr-namespace:redrock.Core" //这里是你的WPhoneApplicationPage类所在的命名空间
cs类文件中
public partial class MainPage : WPhoneApplicationPage // 让MainPage继承WPhoneApplicationPage { public MainPage() { InitializeComponent(); } }
这样你可以在你的ViewModel中使用NavigationService以及重载 ViewModel基类中提供的导航方法