Xamarin Forms Prism:是否需要在构造函数中传递 INavigationService?除了构造函数注入之外的任何其他方式

Xamarin Forms Prism: Is INavigationService necessary to be passed in constructor? Any other way apart from constructor injection

对于 xamarin 形式的棱镜框架,要从一个视图导航到另一个视图,是否必须在 ViewModel 的构造函数中实现构造函数注入并传递 INavigationService

当我通过 INavigationService 作为

时,我可以执行导航
public SomeViewModel(INavigationService navigationService)
{
  _navigationService.NavigateAsync("SomeOtherPage");
}

但是当我在需要时尝试解决时,它不起作用

public SomeViewModel(INavigationService navigationService)
    {
      ContainerProvider.Resolve<T>();// ContainerProvider is IContainerProvider
    }

除了在每个 Viewmodel

中注入构造函数之外,还有其他方法可以访问 INavigationService

您所描述的是一种反模式,通常只是糟糕的设计。它也不会工作,因为导航服务是一项非常特殊的服务。它是专门为每个 ViewModel 创建的,因为导航服务必须具有您从中导航的页面的上下文。没有它,它只能用于重置导航堆栈。尝试在 ViewModel 中以任何其他方式解析导航服务可能会破坏 MVVM 设计模式。

如果您想使用导航服务,您必须通过构造函数注入它。您也可以在 Prism 7.1 中简单地使用 XAML 导航。您可以看到带有 Prism Tests. You can also see this in practice in this demo app.

的示例
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:xaml="clr-namespace:Prism.Navigation.Xaml;assembly=Prism.Forms"
             Title="{Binding Title}"
             x:Class="Prism.DI.Forms.Tests.Mocks.Views.XamlViewMockA">
    <Button x:Name="testButton" Command="{xaml:NavigateTo 'XamlViewMockB'}">
        <Button.CommandParameter>
            <xaml:NavigationParameters>
                <xaml:NavigationParameter Key="Foo" Value="Bar"/>
            </xaml:NavigationParameters>
        </Button.CommandParameter>
    </Button>
</ContentPage>