Silverlight:如何绑定到父视图的DataContext?
我有一个 ParentView,其中包含一个 childView
<UserControl ... x:Name="MyParentView">
<Grid>
<sdk:TabControl Name="ContactTabControl">
<sdk:TabItem Header="Contact" Name="CustomerTabItem">
<Grid>
<Views:CustomerView/>
</Grid>
</sdk:TabItem>
</sdk:TabControl>
</Grid>
</UserControl>
在我的 CustomerView 中,我想将 Firstname 文本框绑定到 Parent 的 DataContext。我在 CustomerView 中尝试过此操作:
<TextBox Text={Binding ElementName=MyParentView, Path=DataContext.Firstname} />
我感觉 CustomerView 根本无法看到其父级,因此永远找不到 ElementName“MyParentView”。
您对此有何建议?
I have a ParentView that contains a childView
<UserControl ... x:Name="MyParentView">
<Grid>
<sdk:TabControl Name="ContactTabControl">
<sdk:TabItem Header="Contact" Name="CustomerTabItem">
<Grid>
<Views:CustomerView/>
</Grid>
</sdk:TabItem>
</sdk:TabControl>
</Grid>
</UserControl>
Within my CustomerView I would like to bind the Firstname textbox to Parent's DataContext. I have tried this inside the CustomerView:
<TextBox Text={Binding ElementName=MyParentView, Path=DataContext.Firstname} />
I have the feeling that CustomerView won't be able to see its parent at all, hence the ElementName "MyParentView" would never be found.
What is your advice on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我做了类似的事情,但我只是将其直接绑定到 Path ,考虑到如果我不给它明确的数据上下文,它会查找层次结构并找到匹配的层次结构。
因此,这应该可以满足您的需求:
如果您需要指定显式数据上下文,您可以随时执行以下操作:
I've done a similar thing but I just bound it directly to Path considering that if I don't give it explicit data context, it will lookup the hierarchy and find one that matches.
So this should get you what you want:
if you need to specify explicit datacontext you can always do:
Maverik 的替代解决方案是:
1 在客户视图中定义依赖属性:
2 修改客户视图的文本框以绑定到此依赖属性(注意元素绑定“this”)
3 修改父视图并将其 DataContext 绑定到新视图依赖属性
4 设置父级的 DataContext
瞧,它可以工作了。不是最优雅的解决方案,但它可以完成您的场景的工作
An alternative solution to Maverik's is :
1 Define a dependency property in your customer view :
2 Modify the customer view's textbox to bind to this dependency property (note the element binding "this")
3 Modify the parent view and bind it's DataContext to the new dependency property
4 Set the parent's DataContext
Voila' it works. Not the most elegant solution but it gets the job done for your scenario