Search code examples
c#inheritancederived-class

Notify derived classes about property changes


In my application I have a base class that defines a property. I then create some classes A, B and C which inherit from the base class.

public class BaseClass {
    private static _prop;

    public PropType Prop {
        get { return _prop; }
        set {
            _prop = value;
            NotifyPropertyChanged("Prop");
        }
    }

    public BaseClass() {}
}

public class A : BaseClass {
    public A() {}

    private void someMethod() {
        Prop = new PropType();
    }
}

In the derived classes I set property values of properties of the base class that affect the other derived classes B and C. What I want to do is to notify all derived classes that a property has changed. How can I do this?

Thanks in advance.

EDIT according to comment of sehe.


Solution

  • Ok, I have even found a solution that seems to work. I defined the Prop-property in the base class as a static property. In the constructor of the derived classes I registered an static event handler to the PropertyChanged event of the base class. The code now looks like that:

    public abstract class BaseClass {
        private static _prop;
        static event PropertyChangedEventHandler PropertyChanged;
    
        private static void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(null, new PropertyChangedEventArgs(propertyName));
            }
        }
    
        public static PropType Prop {
            get { return _prop; }
            set {
                _prop = value;
                NotifyPropertyChanged("Prop");
            }
        }
    
        public BaseClass() {}
    
        protected abstract void BaseVM_PropertyChanged(object sender, PropertyChangedEventArgs e);
    }
    
    public class A : BaseClass {
        public A() {
            base.PropertyChanged += BaseVM_PropertyChanged;
        }
    
        protected override void BaseVM_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            // react on property changes here
        }
        private void someMethod() {
            Prop = new PropType();
        }
    }
    

    Note that you have to implement a static PropertyChanged event and the according static NotifyPropertyChanged-method in BaseClass, regardless if BaseClass derives from another base class that already implements INotifyPropertyChanged.