2011-09-27 41 views
12

我有一个基本的UserControl,设置其DataContext以自身为便于结合:设置DataContext的是影响绑定在父母

<UserControl x:Class="MyControlLib.ChildControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 

      DataContext="{Binding RelativeSource={RelativeSource Self}}"> 

</UserControl> 

这是在父XAML文件中使用这样的:

<UserControl x:Class="MyControlLib.ParentControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:ctrl="clr-namespace:MyControlLib"> 

      <ctrl:ChildControl x:Name="ChildName" 
           PropertyOnChild="{Binding PropertyInParentContext}"/>    
</UserControl> 

由于某种原因,这给出了一个绑定错误,似乎表明父控件的DataContext受到子控件设置自己的DataContext的影响。

System.Windows.Data Error: 40 : BindingExpression path error: 'PropertyInParentContext' property not found on 'object' ''ChildControl' (Name='ChildName')'. BindingExpression:Path=PropertyInParentContext; DataItem='ChildControl' (Name='ChildName'); target element is 'ChildControl' (Name='ChildName'); target property is 'PropertyOnChild' (type 'whatever')

为什么“PropertyInParentContext”正在子控件,而不是在寻找父母的DataContext

如果我从孩子控制删除

DataContext="{Binding RelativeSource={RelativeSource Self}} 

,那么事情操作我怎么会想到。

我在这里错过了一些明显的东西吗?

回答

11

您的控件声明和实例化基本上是操作同一个对象,声明中设置的所有属性也都设置在每个实例上。因此,如果性质是“看得见”可以这么说:

<UserControl x:Class="MyControlLib.ParentControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:ctrl="clr-namespace:MyControlLib"> 
    <ctrl:ChildControl x:Name="ChildName" 
         DataContext="{Binding RelativeSource={RelativeSource Self}}" 
         PropertyOnChild="{Binding PropertyInParentContext}"/> 
</UserControl> 

这就是为什么你没有设置的UserControlsDataContext,它会覆盖继承DataContext(甚至混淆事实,那就是不同的上下文中) 。如果要在其声明中绑定到UserControl的属性,请为该控件命名并使用ElementNameRelativeSource -bindings。

+0

谢谢,我误解了绑定的范围,你的帖子解释得很好。我在想,UserControl的XAML是自包含的,就像在模板中一样,但我想这只是文档的一部分。 – GazTheDestroyer

5

Self意味着UserControl,所以当你设置DataContextSelf,您正在设置DataContextUserControl对象。

绑定到控件的DataContext的正确语法是{Binding RelativeSource={RelativeSource Self}, Path=DataContext},但由于DataContext由Parent继承,因此在任何情况下此绑定都是完全没有意义的。

此外,如果您将DataContext绑定到Self.DataContext,那么您将基本上创建一个将值绑定到自身的循环。

+0

是的,这正是我想要做的 - 将DataContext设置为UserControl。我不明白这会影响“父母”控制中的约束性陈述。 – GazTheDestroyer