I have a basic UserControl
that sets its DataContext
to itself for ease of binding:
<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>
This is used in a parent XAML file like this:
<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>
For some reason, this gives a binding error that seems to indicate that the DataContext
of the parent control is getting affected by the child control setting its own 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')
Why is "PropertyInParentContext" being looking for in the child control rather than in the parent's DataContext
?
If I remove the
DataContext="{Binding RelativeSource={RelativeSource Self}}
from the child control, then things operate how I would expect.
Am I missing something obvious here?