我怎样通知父母属性子属性被改变了

本文关键字:属性 改变 父母 通知 | 更新日期: 2023-09-27 18:16:06

我有以下代码,我想有一种方式,在p1的变化是可见的直接访问或propertygrid。谢谢你的帮助

public class A
{
    int _c = 0;
    public int p1 //this is child property
    {
        get { return _c; }
        set { _c = value; } //here change, notify class B that p1 is changed
    }
}
public class B
{
    A _a = new A();
    public A p2  //this is parents property
    {
        get { return _a; }
        set { _a = value; }
    }
}

我怎样通知父母属性子属性被改变了

。. NET有一个内置的接口,INotifyPropertyChanged。

你要做的是让setter引发事件然后父类订阅事件

public class A : INotifyPropertyChanged
{
    int _c = 0;
    public int p1 //this is child property
    {
        get { return _c; }
        set 
        {
            if(_c != value)
            {
                 OnNotifyPropertyChanged("p1");
                 _c = value;
            } 
        } 
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnNotifyPropertyChanged(string propertyName)
    {
       var tmp = PropertyChanged;
       if (tmp != null)
       {
          tmp (this, new PropertyChangedEventArgs(propertyName));
       }
    }
}
public class B
{
    Public B()
    {
       _a = new A();
       _a.PropertyChanged += AChanged;
    }
    A _a;
    private AChanged(object o, PropertyChangedEventArgs e)
    {
        if(e.PropertyName == "p1")
        {
            //do your work here on change
        }
    }
    public A p2  //this is parents property
    {
        get { return _a; }
        set 
        {
           if(Object.ReferenceEquals(_a, value) == false)
           {
              _a.PropertyChanged -= AChanged; //unsubcribe from the old event
              value.PropertyChanged += AChanged; //subscribe to the new event
           }
           _a = value;
        }
    }
}

首先你需要知道这不是父子关系,它是组合。如果你想要继承,我将告诉你如何通过下面的代码来实现你的目标。

public class A:B
{
    int _c = 0;
    public int p1 //this is child property
    {
        get { return _c; }
        set { _c = value; isChiledchanged= true; } //here change, notify class B that p1 is changed
    }
}
public class B
{
   public bool isChildchanged = false;

}