Using PropertyChanged from reflection

2.1k views Asked by At

I want to get a notification when object attribute is changed by using reflection.

This is one of class in mjpeg.dll:

public class MJPEGConfiguration : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string psw;
        public string   password
        {
            get
            {
                return psw;
            }
            set
            {
                psw = value;
                OnPropertyChanged("PSW");
            }
        }

        public virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

In my camera.cs, I set the MJPEGConfiguration object to "object Configuration" and add a PropertyChanged event to this object:

    public object Configuration
    {
        get 
        {
            return configuration; 
        }
        set
        {
            configuration = value;

            Type t = configuration.GetType(); //t is the type of "MJPEGConfiguration"
            EventInfo ei = t.GetEvent("PropertyChanged");
            MethodInfo mi = this.GetType().GetMethod("My_PropertyChanged");
            Delegate dg = Delegate.CreateDelegate(ei.EventHandlerType, mi);
            ei.AddEventHandler(configuration, dg);
        }
    }

    public void My_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {

    }

However, I'm getting ArgumentException(Error binding to Target Method) in the line of "Delegate dg = ...." How can I fix this problem? Or is there any correct way to do this?

1

There are 1 answers

1
Ritch Melton On BEST ANSWER

The overload of .CreateDelegate you are calling is trying to bind to a static method. For an instance method, do this:

Delegate dg = Delegate.CreateDelegate(et, value, mi);