我的父 View 模型包含几个 subview 模型,看起来像
public MainViewModel:ObservableObject
{
public MainViewModel(){//initalize everything};
private SomeViewModel childvm1;
private AnotherViewModel childvm2;
public SomeViewModel Childvm1
{
get
{
return childvm1;
}
set
{
SetField(ref childvm1, value, "Childvm1");
}
}
public AnotherViewModel Childvm2
{
get
{
return childvm2;
}
set
{
SetField(ref childvm2, value, "Childvm2");
}
}
//when this changes i want to notify childvm2 and call a function in it
public SomeModel SelectedValueofChildvm1
{
get
{
return Childvm1.SelectedValue;
}
}
}
当 SelectedValueofChildvm1
发生变化时,如何调用 childvm2
中的函数?
最佳答案
您必须订阅 subview 模型的 PropertyChangedEvent,如下所示:
public SomeViewModel Childvm1
{
get
{
return childvm1;
}
set
{
if (childvm1 != null) childvm1.PropertyChanged -= OnChildvm1PropertyChanged;
SetField(ref childvm1, value, "Childvm1");
if (childvm1 != null) childvm1.PropertyChanged += OnChildvm1PropertyChanged;
}
}
private coid OnChildvm1PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// now update Childvm2
}
但要小心:
- 您可能还需要在 Childvm2 setter 中更新 childvm2
- 您需要确保 childvm1 实例的生命周期不会超过 MianViewModel 实例,或者在将 MainViewModel 返回给垃圾收集器之前将 Childvm1 设置为 null。
关于c# - 在父 View 模型中公开 subview 模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19638606/