4
votes

I have a ContentPage with some controls and a custom navigationcontrol(ContentView). The contentpage and navigationcontrol both have their respective ViewModels which their BindingContext is set to. Now I need to pass information from the page to the navigationControl.

What I tried:

 <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 is a custom BindingProperty in my navigationControl. The property works, but the BindingContext is wrong, it tries to bind to a "Page" property in the navigationcontrol's ViewModel.

If I change it like so:

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

then it doesn't work either, because it tries to bind to the ContentPage itself instead of its ViewModel. What I would need is to bind it to the ContentPage's ViewModel which has the Page Property I want to read from.

Is my approach wrong altogether? Should I use the MessagingCenter? I'm quite new to Xamarin Forms. Can anyone tell me how to do this properly please?

1

1 Answers

2
votes

For anyone stumbling over a similar issue, this is how I solved it. I'm not completely happy about the solution, but it works:

I have the control ViewModel as a Property in my page ViewModel and set it programmatically:

NavigationViewModel = App.VmLocator.PageNavigationViewModel;

in xaml I set the BindingContext of my custom control to the Property:

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

Now I have access to the control ViewModel in my PageView Model and can pass the data I need there.