好吧,这个看起来很简单,但是我想必须非常熟悉xamarin和XAML sintax并知道它的功能。
场景
我将Xamarin与Prism一起使用,因此我具有ViewModelLocator Autowire的功能,因此在提交您的回复时请记住这一点。
好,可以说我有一个 ContentPage(MainPage),并且此页面上的子组件类型为 ContentView(CustomNavBar)。对于ContentPage
现在Prism很酷,我可以通过约定或自定义方式注册我的视图模型,在这个示例中,我们明确地注册了它们(出于安全考虑)
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
//Registering Navigation
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<MainPage>, MainPageViewModel>();
//I wish i could register the model of an object of type
//ContentView but I cant :( hence this post :P
}
为清楚起见,我可以确认我的ContentPagem.xaml已正确绑定到其视图模型,现在,由于我无法使用上述代码将模型绑定到ContentView(ChildView),下一个逻辑解决方案是将绑定上下文从父级注入到子级,如果您执行以下操作,效果很好:
<!--Snippet from my MainPage.xaml (ContentPage)-->
<local:CustomNavBar BindingContext="{Binding CurrentUser}" />
这也可以正常工作,我的childView(CustomNavBar.xaml)将可以访问CurrentUser对象的所有属性
我的问题是 如果MainPage.xaml(内容页面/父级)具有“委托”命令,我想传递给childView(CustomNavBar.xaml),那么我将如何传递它?理想情况下,我想将ContentPage(MainPage.xaml)的相同视图模型传递给ChildView(CustomNavBar.xaml),换句话说,如何将bindingContext传递为当前视图?
<!--How do i pass the current viewmodel to this contentview-->
<local:CustomNavBar BindingContext="{Binding <this viewmodel>}" />
我已经通过将委托命令包装在一个对象中,然后将该对象传递到contentview来解决了我的问题,但是我的问题是如何通过将当前的viewmodel传递给子对象来做到这一点?
注意:我希望我设置正确的上下文,请避免围绕以下问题提出建议:“为什么不直接使用IEventAggregator或其他任何建议注册到事件。我想说的很清楚”,对此的任何见解都会受到高度赞赏:)谢谢。
答案 0 :(得分:-1)
因此,为了确保我能很好地理解您,您的问题是您拥有具有View 1的Page A,并且想要将BindingContext从PageA传递给View1,对吗?
在这种情况下,您不必做任何事情,因为一旦将View1包含到PageA中,该视图便具有绑定上下文
<ContentPage Title="{Binding MyTitle}">
<StackLayout IsVisibile="{Binding IsGroup1Showen}">
<Label Text ="{Binding UserName}">
</StackLayout>
</ContentPage>
在示例中,StackLayout是一个视图,就像您正在使用的自定义视图一样。 在视图模型中查看视图的绑定上下文的一种好方法是选中OnBindingContextChanged方法并参见。