C# 如何从子ViewModel访问父ViewModel属性?
我有一个带有属性的ParentViewModelC# 如何从子ViewModel访问父ViewModel属性?,c#,wpf,mvvm,C#,Wpf,Mvvm,我有一个带有属性的ParentViewModel class ParentViewModel : BaseObservableObject { private string _text = ""; public string Text //the property { get { return _text; } set { _text = value; O
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,我想从中访问parents“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#中的字符串是不可变的。然后我尝试将父对象作为构造函数参数发送,但我不想将整个父对象作为构造函数参数发送。这就是我如何从内部设置parents属性的方法
parentViewModel.Text += "some text";
编辑:我试图从其子VM访问父VM属性,以便从子VM内部对其进行设置,并在父VM中对其进行更改。最后,我学习了Mediator模式,这是一种存储操作并从任何地方访问操作的方法。对于ViewModels之间的通信,我建议使用一些包含在许多MVVM框架中的Messenger模式实现,例如:
作为一个有点脏的解决方案,您可以传递一个
操作
,而不是字符串属性显示您的代码,这只是一个属性getter/setter,显示您尝试过的代码。参数没有更改的原因是字符串是不可变的,请参阅@Charleh我添加了一些代码示例这很有效,谢谢,我将确定检查messenger模式
public ChildViewModel(Action<string> updateText)
{
updateText("my new value")
}
new ChildViewModel(x => Text = x);