2011-03-06 14 views
-1

我想通過使用反射更改對象屬性時發出通知。從反射中使用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對象爲「對象配置」和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) 
    { 

    } 

但是,我得到ArgumentException(錯誤綁定到目標方法)在「Delegate dg = ....」 我該如何解決這個問題?或者有沒有正確的方法來做到這一點?

+0

如果答案對您有幫助,請隨時將其標記爲已接受。如果不是,請添加評論爲什麼。 – 2011-03-06 17:13:54

回答

0

您正在調用的.CreateDelegate的重載嘗試綁定到靜態方法。對於實例方法,請執行以下操作:

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

PS - 您可能想重新考慮使用Object作爲Configuration的類型。我會爭論使用具體類型或接口。使用其中之一可以讓您擺脫反射代碼。 – 2011-03-06 05:18:28