2013-07-27 128 views
-1

我见过类似的问题,但我仍然无法满足我的需求。我需要输出复选框的名称通过标签的用户控件中:如何从用户控件绑定到父控件的属性?

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> 

如何正确做呢?我缺乏什么知识?感谢帮助。

+0

你为什么要这样做?你可以在你的UserControl中创建一个获得父控件名称或者其他值的属性。 – Clemens

+0

如果我在代码隐藏方面做到这一点,那么查看xaml标记就不会轻易被注意到。这就是为什么我需要一种XAML方式。 – despero

回答

1

上述解决方案将工作,但对于这个特定的问题更直接的解决办法是使用的RelativeSource在用户控件如下结合:

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

希望这是什么你需要 !!!

1

ElementName绑定在same XAML scope内工作。这将工作 -

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

但是,如果你想这样做不同的用户控件,你必须调整了一下你的代码,并使用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"/> 
+0

有点棘手,但有效。谢谢。 – despero

+0

如果它解决了您的查询,您能接受答案吗? –

+1

这就是我正在寻找标签。谢谢 – csensoft

相关问题