我有以下 Contentpage.content,我在其中设置了某些绑定上下文。
<StackLayout>
<local:Post />
<local:Comments />
</StackLayout>
在 Post.xaml.cs (ContentView) 中,我尝试以这种方式获取 ContentPage 的绑定上下文,但它不起作用。
BindingContext = (PostViewModel)Parent.BindingContext;
如果我站在 ContentView 中,如何获取 ContentPage 的绑定上下文?
当你的构造函数被调用时,BindingContext
可能尚未初始化。
所以,你应该等待BindingContext
被更改为对其执行操作。
我认为答案是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.
}
笔记:
如果你有一个ContentView
里面一个ContentPage
,除非由另一个控件(例如使用 ListView 的 ItemTemplate 时)或您的代码显式设置,否则BindingContext
ContentView 的内容与 ContentPage 相同。
所以,没有必要称呼“家长”。
如果需要更多说明,请告诉我。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)