2010-07-19 50 views
0

當我做這樣的事情:問題用的NumericUpDown類型

public static void BindData<T>(this System.Windows.Forms.Control.ControlCollection controls, T bind) 
    { 
     foreach (Control control in controls) 
     { 
      if (control.GetType() == typeof(System.Windows.Forms.TextBox) || control.GetType().IsSubclassOf(typeof(System.Windows.Forms.TextBox))) 
      { 
       UtilityBindData(control, bind); 
      } 
      else 
      { 
       if (control.Controls.Count == 0) 
       { 
        UtilityBindData(control, bind); 
       } 
       else 
       { 
        control.Controls.BindData(bind); 
       } 
      } 
     } 
    } 

    private static void UtilityBindData<T>(Control control, T bind) 
    { 
     Type type = control.GetType(); 

     PropertyInfo propertyInfo = type.GetProperty("BindingProperty"); 
     if (propertyInfo == null) 
      propertyInfo = type.GetProperty("Tag"); 

// rest of the code.... 

其中控制是System.Windows.Forms.Control.ControlCollection,並且被作爲參數傳遞給這段代碼通過了窗體上的控件中有NumericUpDowns,我不能找到他們在控件集合(controls = myForm.Controls)中,但有其他類型的控件(updownbutton,updownedit)。問題是,我想獲得NumericUpDown的標籤屬性,只是不能得到它時,使用遞歸方法檢查表單控件。

回答

1

Tag propertyControl類定義。

因此,你根本不需要反思;你可以簡單地寫

object tag = control.Tag; 

您的代碼不工作,因爲該控件的實際類型(例如,NumericUpDown)沒有定義單獨Tag屬性,GetProperty不搜索基類的屬性。


順便說一句,在你第一次if statemeant,你可以簡單地寫

if (control is TextBox) 
+0

是的,但仍然control.Tag當屬無效。 – 0x49D1 2010-07-19 13:19:54

+0

這意味着你沒有設置任何東西。 – SLaks 2010-07-19 13:20:32

+0

我設置numericupdown控件的,位於窗體上,標籤屬性爲一些值..但在循環中沒有NumericUpDown控件..而是有UpDownButton和UpDownEdit。感謝您的第一個「如果」;) – 0x49D1 2010-07-19 13:23:27