我试图将INavigationService
注入我的ViewModel,因此我可以在页面之间导航,但我不知道如何使用参数注册ViewModel。这是我的应用程序:
<prism:PrismApplication xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Unity;assembly=Prism.Unity.Forms"
x:Class="PrismDemo.App" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">
<prism:PrismApplication.Resources>
<ResourceDictionary>
</ResourceDictionary>
</prism:PrismApplication.Resources>
</prism:PrismApplication>
和...
public partial class App
{
INavigationService _navigationService;
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
_navigationService = NavigationService;
NavigationService.NavigateAsync("MainNavigationPage/Start");
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<MainNavigationPage>();
Container.RegisterTypeForNavigation<StartPage, StartPageViewModel>("Start");
Container.RegisterTypeForNavigation<MiddlePage, MiddlePageViewModel>("Middle");
Container.RegisterTypeForNavigation<LastPage, LastPageViewModel>("Last");
}
}
如何将_navigationService
注入ViewModels?
感谢您的帮助
答案 0 :(得分:1)
只要您遵循惯例{MyProjectName}.Views.{MyPage}
和{MyProjectName}.ViewModels.{MyPageViewModel}
要在ViewModel中使用INavigationService
,只需将其添加到构造函数中即可。请记住,它是一个命名服务,因此必须将其命名为navigationService
。您可以在Samples Repo中查看几个示例。
public class MyPageViewModel
{
INavigationService _navigationService { get; }
public MyPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
NavigateCommand = new DelegateCommand<string>(OnNavigateCommandExecuted);
}
public DelegateCommand<string> NavigateCommand { get; }
public async void OnNavigateCommandExecuted(string path) =>
await _navigationService.NavigateAsync(path);
}
答案 1 :(得分:1)
如果您使用Prism
,则应从App
继承PrismApplication
:
而不是public partial class App
应为public partial class App : PrismApplication
。
无需在INavigationService _navigationService;
课程中声明App
,因为它已在PrismApplication
中声明为NavigationService
属性。
Prism
使用IUnityContainer
作为依赖注入框架,这意味着你将在容器中注册的所有内容:
Container.RegisterType<ISomeService, SomeServiceImplementation>();
Unity container will automatically inject in constructor:
在目标类中定义一个构造函数,该构造函数将依赖类的具体类型作为参数。 Unity容器将实例化并注入实例。
PrismApplication
在容器中注册INavigationService
,因此,据我所知,您不需要注册自己的实例,只需添加INavigationService
类型的参数即可视图模型和统一容器的构造函数将注入注册类型的实例。重要的是,您应该为参数准确提供 navigationService 名称,因为Prism
&#34;期望&#34;导航服务的参数名称。