将属性值从父级用户控件传递到子级的 DependencyProperty

问题描述 投票:0回答:1
c# wpf binding dependency-properties
1个回答
0
投票

回答我自己的问题(检查 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)。

© www.soinside.com 2019 - 2024. All rights reserved.