如何从用户控件绑定到父控件的属性?

时间:2013-07-27 06:45:47

标签: wpf wpf-controls

我见过类似的问题,但我仍然无法满足需要。我需要通过用户控件中的标签输出复选框的名称:

Window1.xaml:

<Window x:Class="WpfBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfBinding" Title="Window1" Height="300" Width="300">
    <Grid>
        <CheckBox Name="checkBox1">
            <local:UserControl1></local:UserControl1>
        </CheckBox>
    </Grid>    
</Window>

UserControl1.xaml:

<UserControl x:Class="WpfBinding.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Canvas>
        <Label Content="{Binding ElementName=checkBox1, Path=Name}"></Label>
    </Canvas>
</UserControl>

如何正确完成?我有什么缺乏知识?谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

ElementName绑定适用于same XAML scope。这将有效 -

 <Grid>
    <CheckBox Name="checkBox1"/>
    <Label Content="{Binding ElementName=checkBox1, Path=Name}"/>
</Grid>

但如果您想在不同的UserControl中执行此操作,则必须稍微调整一下代码并使用Tag来保存名称 -

 <Grid>
    <CheckBox Name="checkBox1">
        <local:UserControl1 Tag="{Binding ElementName=checkBox1, Path=Name}"/>
    </CheckBox>
</Grid>

UserControl.xaml

<Canvas>
    <Label Content="{Binding Path=Tag, RelativeSource={RelativeSource
                       Mode=FindAncestor, AncestorType=UserControl}}"/>
</Canvas>

在旁注中,在UserControl中,您知道需要与ElementName = checkBox1绑定,而这只是您绑定的名称。它相当于 -

<Label Content="checkBox1"/>

答案 1 :(得分:1)

以上解决方案可行,但针对此特定问题的更直接的解决方案是在您的用户控件中使用RelativeSource绑定,如下所示:

<Canvas>
     <Label Content="{Binding RelativeSource={RelativeSource AncestorType=CheckBox, AncestorLevel=1}, Path=Name}"></Label>
</Canvas>

希望这是你需要的!