【问题标题】:How to pass data from ContentPage ViewModel to ContentView Viewmodel in Xamarin Forms with mvvmLight?如何使用 mvvmLight 将数据从 ContentPage ViewModel 传递到 Xamarin Forms 中的 ContentView Viewmodel?
【发布时间】:2018-04-18 14:36:39
【问题描述】:

我有一个带有一些控件和自定义导航控件(ContentView)的 ContentPage。 contentpage 和 navigationcontrol 都有各自的 ViewModel,它们的 BindingContext 设置为。现在我需要将页面中的信息传递给navigationControl。

我尝试了什么:

 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:controls="clr-namespace:AuditApp.Controls;assembly=App"
                 x:Class="App.Pages.MyPage"
                 x.Name="contentpage">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="9*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            ...other controls...
            <controls:PageNavigationControl Grid.Row="1" Page="{Binding Page}"/>
        </Grid>
    </ContentPage>

Page 是我的 navigationControl 中的自定义 BindingProperty。该属性有效,但 BindingContext 错误,它尝试绑定到导航控件的 ViewModel 中的“页面”属性。

如果我这样改变它:

<controls:PageNavigationControl Grid.Row="1" Page="{Binding Page}" BindingContext="{x:Relative Name=contentpage"}/>

那么它也不起作用,因为它试图绑定到 ContentPage 本身而不是它的 ViewModel。我需要将它绑定到 ContentPage 的 ViewModel,该 ViewModel 具有我想要读取的 Page 属性。

我的方法完全错误吗?我应该使用 MessagingCenter 吗?我对 Xamarin Forms 很陌生。谁能告诉我如何正确地做到这一点?

【问题讨论】:

    标签: c# forms xaml xamarin mvvm-light


    【解决方案1】:

    对于遇到类似问题的任何人,这就是我解决它的方法。我对这个解决方案并不完全满意,但它确实有效:

    我将控件 ViewModel 作为我的页面 ViewModel 中的属性并以编程方式设置它:

    NavigationViewModel = App.VmLocator.PageNavigationViewModel;

    在 xaml 中,我将自定义控件的 BindingContext 设置为属性:

    <controls:PageNavigationControl Grid.Row="1" BindingContext="{Binding NavigationViewModel}"/>
    

    现在我可以访问我的 PageView 模型中的控件 ViewModel 并且可以在那里传递我需要的数据。

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2015-02-05
      • 2022-11-25
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      相关资源
      最近更新 更多