jstuardo
jstuardo

Reputation: 4403

MAUI How to pass the view model to a control in a page

I have this content page:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:TimeApp.ViewModels"
             xmlns:controls="clr-namespace:TimeApp.Controls.Wizard"
             x:Class="TimeApp.Views.EnrolamientoPage"
             x:DataType="vm:EnrolamientoViewModel"
             Title="Enrolamiento">
    <StackLayout Padding="25" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
        <controls:MyCustomControl VerticalOptions="FillAndExpand" BindingContext="{Binding Path=.}" />
    </StackLayout>
</ContentPage>

See the MyCustomControl control. I need to pass the instantiated binding context to it (the view model).

Now I can only pass a property belonging to the view model, and I need to pass the whole view model.

Is it possible?

Upvotes: 1

Views: 825

Answers (1)

Liqun Shen-MSFT
Liqun Shen-MSFT

Reputation: 8220

You could use OnBindingContextChanged event as Jason said

public MyCustomControl()
{
    InitializeComponent();
    BindingContextChanged += MyCustomControl_BindingContextChanged;
}

Get the BindingContext:

private void MyCustomControl_BindingContextChanged(object sender, EventArgs e)
{
    EnrolamientoViewModel viewModel = this.BindingContext as EnrolamientoViewModel;
}

or override OnBindingContextChanged method in ContentView code behind

protected override void OnBindingContextChanged()
{
    base.OnBindingContextChanged();
    var context = BindingContext as EnrolamientoViewModel;
}

Hope it works.

Upvotes: 0

Related Questions