How to get ContentPage's BindingContext from ContentView?

后端 未结 2 1641
情歌与酒
情歌与酒 2021-01-19 08:28

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


      
    
&l         


        
相关标签:
2条回答
  • 2021-01-19 09:00

    The BindingContext of the ContentView is usually also the BindingContext of the ContentPage since it is passed down from the parent.

    So you should not even need to set ContentView.BindingContext if you already set the parent ContentPage.BindingContext.

    If I am missing something, please let me know.

    0 讨论(0)
  • 2021-01-19 09:06

    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.

    0 讨论(0)
提交回复
热议问题