如何从子ViewModel访问父ViewModel属性

  • 本文关键字:ViewModel 访问 属性 c# wpf mvvm
  • 更新时间 :
  • 英文 :


我有一个属性为的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,我想从中访问父母";文本";属性从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";

编辑:我试图从父VM的子VM访问父VM属性,以便从子VM内部设置它,并在父VM中更改它。我最终了解了Mediator模式,这是一种存储操作并从任何地方访问操作的方式。

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

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

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

以及在parent:中创建ChildViewModel

new ChildViewModel(x => Text = x);

最新更新