我有一个带有属性的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";编辑:我尝试从其子VM访问父VM属性,以便从子VM中设置它,并在父VM中对其进行更改。最后,我了解了Mediator模式,这是一种存储操作并从任何尝试访问它们的方法。
发布于 2021-03-13 14:25:38
对于ViewModels之间的通信,我建议实现许多MVVM框架中包含的Messenger模式,例如:
作为有点脏的解决方案,您可以传递一个Action而不是string属性。
https://learn.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);https://stackoverflow.com/questions/66613990
复制相似问题