我的父视图模型包含几个子视图模型,它看起来像
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;
}
}
}
当childvm2
更改时,如何在SelectedValueofChildvm1
中调用某个函数?
答案 0 :(得分:4)
您必须订阅子视图模型的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
}
但要小心:
答案 1 :(得分:1)
这种最简单的方法是使用INotifyPropertyChanged
界面来监听属性更改通知。
public MainViewModel:ObservableObject
{
public MainViewModel(){
//initalize everything
Childvm1.PropertyChanged += (s,e) {
if(e.PropertyName == "SelectedValue") {
// Do what you want
}
};
};
}