从反射中使用PropertyChanged

时间:2011-03-06 04:58:54

标签: c# reflection propertychanged

我希望在使用反射更改对象属性时收到通知。

这是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));
            }
        }
    }

在我的camera.cs中,我将MJPEGConfiguration对象设置为“object Configuration”并将PropertyChanged事件添加到此对象:

    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)
    {

    }

但是,我在“Delegate dg = ....”行中收到ArgumentException(绑定到Target方法的错误) 我该如何解决这个问题?或者有没有正确的方法来做到这一点?

1 个答案:

答案 0 :(得分:1)

您正在调用的.CreateDelegate的重载正在尝试绑定到静态方法。对于实例方法,请执行以下操作:

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