Setting DataContext within UserControl is affecting bindings in parent

孤者浪人 提交于 2019-11-27 14:44:15

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.

Self means the UserControl, so when you set the DataContext to Self, you are setting the DataContext to the UserControl object.

The correct syntax for binding to a Control's DataContext would be {Binding RelativeSource={RelativeSource Self}, Path=DataContext}, however since the DataContext is inherited by the Parent, this binding is totally unncessary in any situation.

Also, if you bind your DataContext to Self.DataContext, you would essentially be creating a loop where a value is bound to itself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!