在Xamarin.Forms中,Prism不支持导航

本文关键字:Prism 不支持 导航 Xamarin Forms | 更新日期: 2023-09-27 18:17:28

我是第一次使用xamarin形式的棱镜。为了用xamarin实现prism,我安装了三个软件包:

  1. 棱镜。核心
  2. 棱镜。形式
  3. Prism.Unity.Forms

并像这样从PrismApplication继承App:

  public partial class App : PrismApplication { }

我想绑定视图与ViewModel从代码后面的文件,像这样:

    this.BindingContext=ViewModelLocator.ViewModelName

为此,我找到了这段代码。此代码位于App.xaml.cs:

protected override void ConfigureViewModelLocator()
{
    base.ConfigureViewModelLocator();
    BindViewModelToView<LoginRegisterViewModel, MainPage>();
}
public void BindViewModelToView<TViewModel, TView>()
{
    ViewModelLocationProvider.Register(typeof(TView).ToString(), () => Container.Resolve<TViewModel>());
}

这是我的ViewModel代码:

public class LoginRegisterViewModel : BindableBase
{
    #region Private variables
    private readonly IPageDialogService _diglogService;
    private readonly INavigationService _navigationService;
    public  Action Test { get; set; }
    #endregion
    #region Constructor
    public LoginRegisterViewModel(IPageDialogService diglogService, INavigationService navigationService)
    {
        _diglogService = diglogService;
         _navigationService = navigationService;
    }
    #endregion
}

当我删除INavigationService时,它工作正常。

但是显示错误:

未处理的例外:

Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "DSMobile.ViewModels.LoginRegisterViewModel", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Prism.Navigation.INavigationService, is an interface and cannot be constructed. Are you missing a type mapping?


异常发生时,容器为:

Resolving DSMobile.ViewModels.LoginRegisterViewModel,(none)    
Resolving parameter "navigationService" of constructor DSMobile.ViewModels.LoginRegisterViewModel(Prism.Services.IPageDialogService diglogService, Prism.Navigation.INavigationService navigationService)
Resolving Prism.Navigation.INavigationService,(none)

在Xamarin.Forms中,Prism不支持导航

我知道这是很久之后的问题,但我解决了这个问题通过手动映射INavigationService到PageNavigatonService像这样

container.Register<INavigationService, PageNavigationService>();

我希望这能帮助到其他遇到这个问题的人。