我有一个基本的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}}
,那么事情操作我怎么会想到。
我在这里错过了一些明显的东西吗?
谢谢,我误解了绑定的范围,你的帖子解释得很好。我在想,UserControl的XAML是自包含的,就像在模板中一样,但我想这只是文档的一部分。 – GazTheDestroyer