Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ContentPage's BindingContext from ContentView?

I have the following Contentpage.content, where I set certain binding context.

<StackLayout>
    <local:Post />  
    <local:Comments />
</StackLayout>

In Post.xaml.cs (ContentView), I've tried to get the binding context of the ContentPage this way but it doesn't work.

BindingContext = (PostViewModel)Parent.BindingContext;

How can I get the binding context of the ContentPage if I'm standing in a ContentView?

like image 933
Fede Berco Avatar asked Jan 06 '23 21:01

Fede Berco


1 Answers

By the time your constructor is called, the BindingContext might not be initialised yet.

So, you should wait for the BindingContext being changed to perform operations on it.

I think the answer is OnBindingContextChanged event. https://developer.xamarin.com/api/member/Xamarin.Forms.View.OnBindingContextChanged()

Little sample:

        protected override void OnBindingContextChanged ()
        {
            base.OnBindingContextChanged ();

            //BindingContext should not be null at this point
            // and you may add your code here.
        }

Note: If you have a ContentView inside a ContentPage, unless explicitly set by another Control (like when using an ItemTemplate for a ListView) or by your code, the BindingContext of the ContentView is the same as the ContentPage.

So, it shouldn't be necessary to call "Parent".

Let me know if more clarification is needed.

like image 173
Rodrigo Elias Avatar answered Jan 08 '23 09:01

Rodrigo Elias