【问题标题】:How to access parent ViewModel property from child ViewModel?如何从子 ViewModel 访问父 ViewModel 属性?
【发布时间】:2021-04-13 07:04:44
【问题描述】:

我有一个带属性的 ParentViewModel

class ParentViewModel : BaseObservableObject
{
    private string _text = "";

    public string Text //the property
    {
        get { return _text; }
        set
        {
            _text = value;
            OnPropertyChanged("Text");
        }
    }

    ChildViewModel _childViewModel;

    public ParentViewModel()
    {
        _childViewModel = new ChildViewModel(Text);
    }

和 ChildViewModel,我想从中访问父级“Text”属性以从 ChildViewModel 内部设置它,我尝试了这个

class ChildViewModel : BaseObservableObject
{

    public string _text { get; set; }

    public ParentViewModel(string Text)
    {
        _text = Text;

        _text += "some text to test if it changes the Text of the parent"; //how I tried to set it
    }

但它不起作用的原因是因为 c# 中的字符串是不可变的。然后我尝试将父对象作为构造函数参数发送,但我不想将整个父对象作为构造函数参数发送。这就是我能够从孩子内部设置父母属性的方式

parentViewModel.Text += "some text";

编辑:我试图从子虚拟机访问父虚拟机属性以从子虚拟机内部对其进行设置,并在父虚拟机中对其进行更改。我最终了解了 Mediator 模式,这是一种存储操作并从您尝试访问的任何位置访问它们的方法。

【问题讨论】:

标签: c# wpf mvvm


【解决方案1】:

对于 ViewModel 之间的通信,我建议使用许多 MVVM 框架中包含的 Messenger 模式的一些实现,例如:
https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/june/mvvm-the-mvvm-light-messenger-in-depth

作为一个有点脏的解决方案,您可以传递 Action 而不是字符串属性
https://docs.microsoft.com/en-us/dotnet/api/system.action-1?view=net-5.0

public ChildViewModel(Action<string> updateText)
{
    updateText("my new value")
}

以及在父级中创建 ChildViewModel:

new ChildViewModel(x => Text = x);

【讨论】:

  • 成功了,谢谢,我一定会检查信使模式
猜你喜欢
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 2013-05-06
相关资源
最近更新 更多