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 the parent XAML file as follows:
<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, which seems to indicate that the DataContext control of the parent affects the setting of the child control to its own DataContext .
System.Windows.Data error: 40: BindingExpression path error: PropertyInParentContext was not found in the 'object' '' ChildControl '(Name =' ChildName ')'. BindingExpression: Path = PropertyInParentContext; DataItem = 'ChildControl' (Name = 'ChildName'); target element is "ChildControl" (Name = "ChildName"); target - property 'PropertyOnChild' (type 'whatever')
Why is the "PropertyInParentContext" looking in the child control and not in the parent DataContext ?
If i remove
DataContext="{Binding RelativeSource={RelativeSource Self}}
from a child control, then everything works as I expected.
Did I miss something obvious here?
data-binding wpf xaml user-controls datacontext
GazTheDestroyer Sep 27 '11 at 15:50 2011-09-27 15:50
source share