如何在父级中绑定子用户控件的数据上下文
问题描述:
<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" />