2017-02-20 76 views
1

我使用MVVM Light創建了Xamarin Forms應用程序。我創建的NavigationService類,並在構造函數中註冊它:MVVM Light - 已經有一家工廠註冊了INavigationService

public App() 
    { 
     InitializeComponent(); 

     // Setup navigation service: 
     var navigationService = new NavigationService(); 
     // Configure pages: 
     navigationService.Configure(AppPages.MainPage, typeof(MainPage)); 
     navigationService.Configure(AppPages.DetailsPage, typeof(DetailsPage)); 
     // Register NavigationService in IoC container: 
     SimpleIoc.Default.Register<INavigationService>(() => navigationService); 

     // Create new Navigation Page and set MainPage as its default page: 
     var firstPage = new NavigationPage(new MainPage()); 
     // Set Navigation page as default page for Navigation Service: 
     navigationService.Initialize(firstPage); 
     // You have to also set MainPage property for the app: 
     MainPage = firstPage; 
    } 

一旦我退出在Android上後退箭頭的應用程序,然後重新打開它,我有例外:

enter image description here

我嘗試不同的方法:註銷並重新註冊服務或檢查服務是否已經註冊,但仍然存在一些問題。我會很感激的幫助。

回答

0

它應該有如下 - 這是正確的,現在工作:

public App() 
    { 
     InitializeComponent(); 

     INavigationService navigationService; 

     if (!SimpleIoc.Default.IsRegistered<INavigationService>()) 
     { 
      // Setup navigation service: 
      navigationService = new NavigationService(); 

      // Configure pages: 
      navigationService.Configure(AppPages.MainPage, typeof(MainPage)); 
      navigationService.Configure(AppPages.DetailsPage, typeof(DetailsPage)); 

      // Register NavigationService in IoC container: 
      SimpleIoc.Default.Register<INavigationService>(() => navigationService); 
     } 

     else 
      navigationService = SimpleIoc.Default.GetInstance<INavigationService>(); 

     // Create new Navigation Page and set MainPage as its default page: 
     var firstPage = new NavigationPage(new MainPage()); 
     // Set Navigation page as default page for Navigation Service: 
     navigationService.Initialize(firstPage); 
     // You have to also set MainPage property for the app: 
     MainPage = firstPage; 
    } 

記住下面添加方法INavigationService接口:

void Configure(AppPages pageKey, Type pageType); 
void Initialize(NavigationPage page);