How to notify client's child classes property changes from my parent class?

1.2k Views Asked by At

I am writing a library and my clients using my library.

My clients creates own classes derived from my base class.

Can i detect my client's class property is changed?

I don't want my clients to implement INotifyPropertyChanged.

I am also using reflection for other purposes. Why reflection can't detect properties change status?

My library code:

public class BaseClass
{
    public void ChildPropertyChanged(propinfo...)
    {
        ...
    }
}

Client's code:

public class MyClass : BaseClass
{
    public string Name {get;set;}
}
2

There are 2 best solutions below

1
On

Your clients must collaborate, meaning they will have to write code to help you catch the change of properties, as in INotifyPropertyChanged clients (implementers) must raise an event (RaisePropertyChanged);

If you think about it, if what you are asking was possible, than INotifyPropertyChanged was not necessary..

One possible solution for you is to define an event in the base class, and guide your clients to raise it in their properties getters, or even better - calling a base class handler method.

2
On

You could implement the template pattern.

Base class.

public class BaseClass
{
    protected string name;

    private void NameChanged()
    {
         ...
    }

    public void SetName(string value)
    {
        this.name = value;
        this.NameChanged();
    }
}

Derived class:

public class MyClass : BaseClass
{
    public string Name 
    {
        get 
        {
            return this.name; 
        }

        set 
        {
            this.SetName(value);
        }
    }
}

Although doing it this way eliminates the need for the property in the derived class - it can be changed using the base class method SetName.