如何在父级中绑定子用户控件的数据上下文 [英] How to bind a child user control's data context in the parent

查看:29
本文介绍了如何在父级中绑定子用户控件的数据上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<TextBlock Text="{Binding ChildGroupName, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, UpdateSourceTrigger=PropertyChanged,NotifyOnTargetUpdated=True,Mode=TwoWay}"
TargetUpdated="OnTextUpdated"/> 

这里的 ChildGroupName 是子控件数据上下文属性.我想将 ChildGroupName 值绑定到父窗口.

Here ChildGroupName is a child control datacontext property. I want to bind ChildGroupName values to parent window.

推荐答案

您不能使用 FindAncestor 将数据绑定到后代的数据...线索就在其名称中.如果子 UserControl 在与父项相同的 XAML 中定义,则您可以为其提供名称,然后使用 Binding.ElementName 属性 将数据绑定到其属性:

You cannot use FindAncestor to data bind to a descendant's data... the clue is in its name. If the child UserControl is defined in the same XAML as the parent, then you can provide it with a name and then use the Binding.ElementName Property to data bind to its properties:

<TextBlock Text="{Binding ChildPropertyName, ElementName=NameOfChildUserControl, 
    UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True, Mode=TwoWay}" 
    TargetUpdated="OnTextUpdated" />

这篇关于如何在父级中绑定子用户控件的数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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