Vahid
Vahid

Reputation: 5444

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>

Upvotes: 0

Views: 3570

Answers (3)

Jai
Jai

Reputation: 8363

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

Upvotes: 3

Markus H&#252;tter
Markus H&#252;tter

Reputation: 7906

if you see the DataContext being null in the codebehind your're checking at a time, when the binding is not yet resolved. You don't happen to check in the constructor do you?

With the binding you got the DataContext should be of Type MyApp.Dialogs.Usercontrol. If you want it to have the same DataContext as the Window just remove the binding altogether.

Upvotes: 1

Rowbear
Rowbear

Reputation: 1669

{Binding RelativeSource={RelativeSource Self}, Path=DataContext}

However, the usercontrol should automatically inherit the datacontext of the window!

Upvotes: 3

Related Questions