如何从ContentView获取ContentPage的BindingContext? [英] How to get ContentPage's BindingContext from ContentView?
问题描述
我有以下Contentpage.content,在其中设置了某些绑定上下文.
<StackLayout>
<local:Post />
<local:Comments />
</StackLayout>
在Post.xaml.cs(ContentView)中,我试图以这种方式获取ContentPage的绑定上下文,但是它不起作用.
BindingContext = (PostViewModel)Parent.BindingContext;
如果我站在ContentView中,如何获取ContentPage的绑定上下文?
在调用构造函数时,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.
}
注意:
如果您在ContentPage
中有一个ContentView
,除非由另一个控件(例如,将ItemTemplate用于ListView)或您的代码明确设置,否则ContentView的BindingContext
与ContentPage相同.>
因此,不必称呼父母".
让我知道是否需要进一步澄清.
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?
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.
这篇关于如何从ContentView获取ContentPage的BindingContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!