Prism Xamarin表单导航服务,DependencyService

时间:2018-05-17 12:09:43

标签: dependency-injection xamarin.forms prism

正如Prism所说,

  

要在ViewModels中获取INavigationService,只需要求它   作为构造函数参数

https://prismlibrary.github.io/docs/xamarin-forms/Navigation-Service.html#getting-the-navigation-service

像这样:

public SpeakPageViewModel(INavigationService navigationService) : base(navigationService)

{

_navigationService = navigationService;

}

我希望使用ITextToSpeech接口作为Prism样本:

public MainPageViewModel(ITextToSpeech textToSpeech)
{
    _textToSpeech = textToSpeech;
    SpeakCommand = new DelegateCommand(Speak);
}

https://prismlibrary.github.io/docs/xamarin-forms/Dependency-Service.html#use-the-service

问题是:在构造函数中添加其他参数时,导航无效。

public SpeakPageViewModel(ITextToSpeech textToSpeech, INavigationService navigationService) : base(navigationService)
        {
            _navigationService = navigationService;
            _textToSpeech = textToSpeech;
        }

项目文件:http://www.mediafire.com/file/nl6dx5c4mc3mg63/FirstPrismApp.rar

1 个答案:

答案 0 :(得分:3)

Prism 7改变了这种行为,因为它实际上是依赖于辅助容器的反模式。您只需在IPlatformInitializer中注册TextToSpeech服务,如:

public class iOSInitializer : IPlatformInitializer
{
    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.Register<ITextToSpeech, TextToSpeech_iOS>();
    }
}