回答我自己的问题(检查 ParentUserControl):
型号:
public class RootModel : ViewModelBase
{
private ParentModel parentModel = new();
public ParentModel ParentModel { get => parentModel; set => RisePropertyChanged(ref parentModel, value); }
}
public class ParentModel : ViewModelBase
{
private ChildModel childModel = new();
public ChildModel ChildModel { get => childModel; set => RisePropertyChanged(ref childModel, value); }
public string ParentModelProperty => "Correct value from ParentModel";
}
public class ChildModel : ViewModelBase
{
private string childModelProperty = "Wrong default value from ChildModel";
public string ChildModelProperty { get => childModelProperty; set => RisePropertyChanged(ref childModelProperty, value); }
}
主窗口:
<Window.DataContext>
<model:RootModel/>
</Window.DataContext>
<uc:ParentUserControl DataContext="{Binding ParentModel}"/>
家长用户控件:
<uc:ChildUserControl ChildDependency="{Binding DataContext.ParentModelProperty, RelativeSource={RelativeSource AncestorType=UserControl}}" DataContext="{Binding ChildModel}"/>
子用户控件:
<StackPanel>
<Label Content="Dependency property:"/>
<Label Content="{Binding ChildDependency, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
<Separator/>
<Label Content="Property:"/>
<Label Content="{Binding ChildModelProperty}"/>
</StackPanel>
public partial class ChildUserControl : UserControl
{
public static readonly DependencyProperty ChildDependencyProperty =
DependencyProperty.Register(nameof(ChildDependency), typeof(string), typeof(ChildUserControl), new ("Wrong default DP value from ChildUserControl"));
public string ChildDependency
{
get => (string)GetValue(ChildDependencyProperty);
set => SetValue(ChildDependencyProperty, value);
}
public ChildUserControl()
{
InitializeComponent();
}
}
这就是如何将属性 (SomeProperty) 从 ParentUserControl 上下文传递到 ChildUserControl 的 DependencyProperty (MyDProperty)。