-3

我有以下代码,我想有一种方法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; }
    }
}
4

2 回答 2

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;
        }
    }
}
于 2013-05-31T04:38:12.240 回答
-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;


}
于 2013-05-31T06:49:44.313 回答