Sunday, 26 October 2008

Accessing Properties from abstract class

I wanted my abstract class to hook into the PropertyChanged event for any Property in the derived class that implements INotifyPropertyChanged.

I use reflection to get all the properties of the derived class then check that they implement the INotifyPropertyChanged interface before adding the event handler.

The Property must be defined in the "traditional" way rather than using the auto-property syntax otherwise the InitializeProperties method in the abstract class has no object to add the event handlers to.
public class Model : AbstractModel
{
private Till _till = new Till();
public Till Till
{
get { return _till; }
set { _till = value; }
}
}
public abstract class AbstractModel : INotifyPropertyChanged
{
public AbstractModel()
{
InitializeProperties();
}

private void InitializeProperties()
{
PropertyInfo[] propertyInfoList = this.GetType().GetProperties();

foreach (PropertyInfo propertyInfo in propertyInfoList)
{
object observedObject = propertyInfo.GetValue(this, null);
if (observedObject is INotifyPropertyChanged)
{
(observedObject as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler(BusinessPropertyChanged);
}
}
}
...
}

No comments: