【问题标题】:Xamarin - Prism: How do I pass the whole ViewModel of the ContentPage to a child ContentViewXamarin - Prism:如何将 ContentPage 的整个 ViewModel 传递给子 ContentView
【发布时间】:2023-04-07 03:21:01
【问题描述】:

好吧,这个看起来很简单,但我想必须非常熟悉 xamarin 和 XAML 语法,并且知道它的功能。

场景

我将 Xamarin 与 Prism 结合使用,因此我拥有 ViewModelLocator Autowire 的强大功能,因此请在提交回复时牢记这一点。

好的,假设我有一个 ContentPage (MainPage),并且该页面有一个类型为 ContentView (CustomNavBar) 的子组件。对于内容页面

现在 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,但我的问题是如何通过将当前视图模型传递给子视图来更清晰、更正确地做到这一点?

注意:我希望我设置正确的上下文,请避免围绕以下问题的建议:“你为什么不使用 IEventAggregator blah blah 或任何其他建议注册一个事件。什么我问的很清楚”对此的任何见解将不胜感激:) 谢谢。

【问题讨论】:

  • 好寂寞……

标签: c# xaml mvvm xamarin.forms prism


【解决方案1】:

所以为了确保我能很好地理解你,你的问题是你的页面 A 有视图 1,并且你想将 BindingContext 从页面 A 传递到 View1,对吗?

在这种情况下,您不必做任何事情,因为一旦将 View1 包含到 PageA 中,那么视图将固有绑定上下文

<ContentPage Title="{Binding MyTitle}">
  <StackLayout IsVisibile="{Binding IsGroup1Showen}">
    <Label Text ="{Binding UserName}">
  </StackLayout>
</ContentPage>

在示例中,StackLayout 是一个视图,就像您正在使用的自定义视图一样。 在视图模型中查看视图绑定上下文的一个好方法是检查 OnBindingContextChanged 方法并查看。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多