Search code examples
wpfxamldata-bindinguser-controlsdatacontext

Bind the data context of user control to main window in WPF


I'm trying to bind the data context of the user control to the data context of the window. But somehow in the code behind of the user control, the data context is null. What am I doing wrong here?

<Window x:Class="MyApp.Dialogs.SettingsWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:dialogs="clr-namespace:MyApp.Dialogs"
        Title="Settings">

    <dialogs:Usercontrol DataContext="{Binding RelativeSource={RelativeSource Self}}"></dialogs:Usercontrol>

</Window>

Solution

  • If MyApp.Dialogs.Usercontrol has defined its own DataContext in its XAML/code-behind, and you are trying to override this, then you can do this:

    <dialogs:Usercontrol DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext}" />
    

    If MyApp.Dialogs.Usercontrol does not have its DataContext explicitly defined, then you don't need to do this at all - it will automatically inherit from its parent (Window).