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