将用户控件的数据上下文绑定到WPF中的main window

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

我正在尝试将用户控件的数据上下文绑定到 window 的数据上下文。但不知何故在用户控件的代码背后,数据上下文为空。我在这里做错了什么?

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

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

但是,用户控件应该自动继承 window!

的数据上下文

如果您在代码隐藏中看到 DataContext 为 null,则您正在检查绑定尚未解析的时间。你不会碰巧签入构造函数吧?

通过绑定,您得到的 DataContext 应该是 MyApp.Dialogs.Usercontrol 类型。如果您希望它具有与 Window 相同的 DataContext,只需完全删除绑定即可。

如果 MyApp.Dialogs.Usercontrol 在其 XAML/code-behind 中定义了自己的 DataContext,而您正试图覆盖它,那么您可以这样做:

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

如果 MyApp.Dialogs.Usercontrol 没有明确定义其 DataContext,那么您根本不需要这样做 - 它会自动从其父级 (Window) 继承。