如何通知父母的财产儿童的财产被更改

时间:2013-05-31 04:11:01

标签: c#

我有以下代码,我希望有一种方法可以在访问直接或propertygrid中看到p1中的更改。 谢谢你的帮助

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; }
    }
}

2 个答案:

答案 0 :(得分:2)

.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;
        }
    }
}

答案 1 :(得分:-1)

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

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;


}