3

我的父视图模型包含几个子视图模型,它看起来像

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

4

2 回答 2

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
}

不过要小心:

  • 您可能还需要在 Childvm2 设置器中更新 childvm2
  • 您需要确保 childvm1 实例不会超过 MianViewModel 实例,或者在将 MainViewModel 返回给垃圾收集器之前将 Childvm1 设置为 null。
于 2013-10-28T15:33:01.750 回答
1

这种最简单的方法是使用INotifyPropertyChanged接口来监听属性更改通知。

public MainViewModel:ObservableObject
{
     public MainViewModel(){
        //initalize everything
        Childvm1.PropertyChanged += (s,e) {
            if(e.PropertyName == "SelectedValue") {
               // Do what you want
            }           
        };
    };

}
于 2013-10-28T15:33:15.827 回答