MVVM How to get notified when nested objects properties are updated?

﹥>﹥吖頭↗ 提交于 2019-12-11 17:16:12

问题


For example

class child : ObservableObject{
  private int _prop;
  public int prop{
    get {
      return _prop;
    }
    set {
      _prop=value;
      OnPropertyChanged("prop");
    }
}
class parent : ObservableObject{
  private child _mychild;
  public child mychild{
    get {
      return _mychild;
    }
    set {
      _mychild=value;
      OnPropertyChanged("mychild");
      OnPropertyChanged("pow");
    }
  }
  public int pow{
    return _mychild.prop*2;
  }
}

parent myobj;
myobj.child.prop=1;

How do I get notified that bar.z is updated? I have binded the nested property and updates the view, but the part where bar.pow is binded does not get updated.

<Textbox Text={Binding myobj.child.prop}/>
<Textbox Text={Binding myobj.pow}/>

What im trying to do is update the second textbox when the first textbox is updated.


回答1:


You have to subscribe in parent object to the PropertyChanged of a child object and notify view in event handler for child.PropertyChanged which properties are impacted. Don't forget to unsubscribe by previous object.

class foo: ObservableObject
{
private int _x;
public int x
{
    get
    {
        return _x;
    }
    set
    {
        _x = value;
        OnPropertyChanged("x");
    }
}
class bar : ObservableObject
{
    private foo _y;
    public foo y
    {
        get
        {
            return _y;
        }
        set
        {
            if (_y!=null)
            {
                _y.PropertyChanged -= _y_PropertyChanged;
            }

            _y = value;
            _y.PropertyChanged += _y_PropertyChanged;

            OnPropertyChanged("y");
            OnPropertyChanged("pow");
        }
    }

    private void _y_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        //if(e.PropertyName == "x");
        //{
        OnPropertyChanged("pow");
        OnPropertyChanged("y");
        //}
    }

    public int pow { get { return _y.x * 2;} }
}


来源:https://stackoverflow.com/questions/52850788/mvvm-how-to-get-notified-when-nested-objects-properties-are-updated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!