繁体   English   中英

如何使用mvvmLight在Xamarin Forms中将数据从ContentPage ViewModel传递到ContentView Viewmodel?

[英]How to pass data from ContentPage ViewModel to ContentView Viewmodel in Xamarin Forms with mvvmLight?

我有一个带有某些控件的ContentPage和一个自定义的navigationcontrol(ContentView)。 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>

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

如果我这样更改它:

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

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

我的方法完全错误吗? 我应该使用MessagingCenter吗? 我对Xamarin Forms很陌生。 有人可以告诉我如何正确执行此操作吗?

对于任何遇到类似问题的人,这就是我解决的方法。 我对该解决方案并不完全满意,但是它可以工作:

我在页面ViewModel中将控件ViewModel作为属性,并以编程方式进行设置:

NavigationViewModel = App.VmLocator.PageNavigationViewModel;

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM