我正在尝试从ViewModel
导航到新的导航页面我在App.cs中有这个片段,它创建一个新的导航页面并将ViewModel绑定到View
MainPage = new NavigationPage((Page)ViewFactory.CreatePage<MainViewModel, MainView>());
该片段来自本文getting started xamarin forms labs xaml mvvm ioc @“5。使用ViewFactory注册视图”
但是我们如何在ViewModel中执行此操作,并且当我们使用ViewFactory.Register绑定它们时,创建新页面并将ViewModel和View绑定在一起是否有意义?
文章摘录:
public class App : Application
{
public App()
{
RegisterViews();
MainPage = new NavigationPage((Page)ViewFactory.CreatePage<MainViewModel, MainView>());
}
private void RegisterViews()
{
ViewFactory.Register<MainView, MainViewModel>();
}
}
答案 0 :(得分:2)
我确定不能很好地解决你的问题但是,这就是我所做的: 首先在你的AppDelegate(或主活动)中注册你的依赖注入模块(这里是一个simpleContainer的IDependencyContainer):
var resolverContainer = new SimpleContainer();
UserService us = new UserService();
var app = new XFormsAppiOS();
resolverContainer.Register<IDevice>(t => AppleDevice.CurrentDevice)
.Register<IDisplay>(t => t.Resolve<IDevice>().Display)
.Register<IXFormsApp>(app)
.Register<IJsonSerializer, JsonSerializer>()
.Register<IDependencyContainer>(resolverContainer);
Resolver.SetResolver(resolverContainer.GetResolver());
然后在你的app.cs上,一定要注册导航服务以进入你的主导航页面
Page loginPage = new NavigationPage((LoginPage)ViewFactory.CreatePage<LoginViewModel, LoginPage>());
MainPage = loginPage;
Resolver.Resolve<IDependencyContainer>()
.Register<INavigationService>(t => new NavigationService(MainPage.Navigation)) //New Xlabs nav service
.Register<INavigation>(t => MainPage.Navigation); // old Xlabs nav service
在你的viewModel推送页面中你需要
await Resolver.Resolve<INavigation>().PushAsync((ParameterPage)ViewFactory.CreatePage<ParameterViewModel, ParameterPage>(), false);