如何从 ContentView 获取 ContentPage 的 BindingContext? [英] How to get ContentPage's BindingContext from ContentView?

查看:14
本文介绍了如何从 ContentView 获取 ContentPage 的 BindingContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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;

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

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

推荐答案

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

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

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

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

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

I think the answer is OnBindingContextChanged event. 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.
        }

注意:如果您在 ContentPage 中有一个 ContentView,除非由另一个控件明确设置(例如在为 ListView 使用 ItemTemplate 时)或您的代码,BindingContext 与 ContentPage 相同.

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.

因此,没有必要调用Parent".

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

如果需要更多说明,请告诉我.

Let me know if more clarification is needed.

这篇关于如何从 ContentView 获取 ContentPage 的 BindingContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆