在父视图模型中公开子视图模型的属性

时间:2013-10-28 15:20:02

标签: c# wpf mvvm

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

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中调用某个函数?

2 个答案:

答案 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
}

但要小心:

  • 您可能还必须在Childvm2 setter中更新childvm2
  • 您需要确保childvm1实例不会超过MianViewModel实例,或者在将MainViewModel返回给垃圾收集器之前将Childvm1设置为null。

答案 1 :(得分:1)

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

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

}