MVVM Light - 已经为INavigationService

时间:2017-02-20 05:32:05

标签: xamarin xamarin.forms mvvm-light

我有MVVM Light的Xamarin Forms应用程序。我创建了NavigationService类并在构造函数中注册它:

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

我尝试了不同的方法:取消注册并再次注册服务或检查服务是否已注册,但仍存在一些问题。我很感激你的帮助。

1 个答案:

答案 0 :(得分: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);