如何从ContentView获取ContentPage的BindingContext?

时间:2016-06-16 19:29:33

标签: xamarin xamarin.forms

我有以下Contentpage.content,我在其中设置了某些绑定上下文。

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

在Post.xaml.cs(ContentView)中,我试图以这种方式获取ContentPage的绑定上下文,但它不起作用。

BindingContext = (PostViewModel)Parent.BindingContext;

如果我站在ContentView中,如何获取ContentPage的绑定上下文?

2 个答案:

答案 0 :(得分:7)

到调用构造函数时,BindingContext可能尚未初始化。

因此,您应该等待BindingContext被更改以对其执行操作。

我认为答案是OnBindingContextChanged事件。 https://developer.xamarin.com/api/member/Xamarin.Forms.View.OnBindingContextChanged()

小样本:

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

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

注意: 如果ContentView内有ContentPage,除非由另一个Control显式设置(比如使用ListView的ItemTemplate)或代码,否则ContentView的BindingContext是相同的作为ContentPage。

因此,没有必要调用“Parent”。

如果需要进一步澄清,请告诉我。

答案 1 :(得分:0)

BindingContext的{​​{1}}通常也是ContentView的{​​{1}},因为它是从父母传下来的。{/ p>

因此,如果您已经设置了父BindingContext,则甚至不需要设置ContentPage

如果我遗失了什么,请告诉我。

相关问题