0

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.

bheek
  • 11
  • 3

1 Answers1

-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;} }
}
Rekshino
  • 6,954
  • 2
  • 19
  • 44
  • You don't need `OnPropertyChanged("y");` in `_y_PropertyChanged()` - that's already handled by the y property setter. – Peregrine Oct 17 '18 at 10:10
  • @Peregrine The change on x is not handled in y setter. In y setter is only handled change of y itself. – Rekshino Oct 17 '18 at 10:12
  • @Peregrine For the particular case we don't need `OnPropertyChanged("y")`, but as object `y` being changing, it is right to notify this change. – Rekshino Oct 17 '18 at 10:20
  • @Rekshino It probably doesn't make any notable difference in this case, but every (unnecessary) NotifyPropertyChanged event will decrease the efficiency of your application. In general, you only want to send a NotifyPropertyChanged event when a property value has actually changed, not just because one of its child properties has changed. – Peregrine Oct 17 '18 at 10:25