Setting DataContext within UserControl is affecting bindings in parent

The declaration of your control and the instantiation are basically manipulating the same object, all the properties that are set in the declaration are also set on every instance. So if the properties were “visible” so to speak:

<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>

This is why you do not set the DataContext of UserControls, it will override the inherited DataContext (and even obfuscate the fact that there is a different context). If you want to bind to properties of the UserControl in its declaration then name the control and use ElementName or RelativeSource-bindings instead.

Leave a Comment