【发布时间】: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 模式,这是一种存储操作并从您尝试访问的任何位置访问它们的方法。
【问题讨论】:
-
显示你的代码,这只是一个属性getter/setter,显示你尝试过的代码。
-
参数不变的原因是字符串是不可变的,见docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…
-
@Charleh 我添加了一些代码示例