2010-05-03 38 views
5

[編輯]爲清楚起見,我知道如何通過反射獲取表單列表。我更關心設計時間屬性網格。Visual Studio設計時間屬性 - 表單列表下拉

我有一個類型爲Form的公共屬性的用戶控件。
我希望能夠在設計時從下拉列表中選擇一個表格。
我想從一組命名空間填充表單下拉列表:UI.Foo.Forms

這將工作,如果你有一個公共屬性的控制。在設計時,該屬性會自動填充表單上所有控件的下拉列表,供您選擇。我只是想用名稱空間中的所有表單填充它。

我該如何去做這件事?我希望我已經夠清楚了,所以沒有混淆。我正在尋找一些代碼示例,如果可能的話。我想盡量避免在我有其他最後期限會面時花費太多時間。

感謝您的幫助提前。

回答

7

您可以輕鬆地通過反射獲取類:

var formNames = this.GetType().Assembly.GetTypes().Where(x => x.Namespace == "UI.Foo.Forms").Select(x => x.Name); 

假設你從代碼在同一程序作爲你的形式調用這個,你會得到那些在所有類型的名稱「UI.Foo.Forms」命名空間。然後,您可以在下拉菜單中介紹這一內容,最終,實例取其由用戶通過反射選擇一次:

Activator.CreateInstance(this.GetType("UI.Form.Forms.FormClassName")); 

[編輯]添加代碼設計時的東西:

在你的控制你可以創建Form屬性,如下所示:

[Browsable(true)] 
[Editor(typeof(TestDesignProperty), typeof(UITypeEditor))] 
[DefaultValue(null)] 
public Type FormType { get; set; } 

其中引用了必須定義的編輯器類型。該代碼非常明瞭,只需進行最少量的調整,您就可以使其完全按照您的要求生成。

public class TestDesignProperty : UITypeEditor 
{ 
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) 
    { 
     return UITypeEditorEditStyle.DropDown; 
    } 

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) 
    { 
     var edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); 

     ListBox lb = new ListBox(); 
     foreach(var type in this.GetType().Assembly.GetTypes()) 
     { 
      lb.Items.Add(type); 
     } 

     if (value != null) 
     { 
      lb.SelectedItem = value; 
     } 

     edSvc.DropDownControl(lb); 

     value = (Type)lb.SelectedItem; 

     return value; 
    } 
} 
+0

我知道如何獲得表格列表,但我不知道如何在設計時在設計視圖中爲我的公共屬性在屬性網格中填充這些內容。 – 2010-05-06 01:33:57

+0

更新我的答案以解決設計時要求。 – CMerat 2010-05-06 02:01:37

+1

謝謝梅拉特,我必須再等14個小時才能接受(去土耳其狩獵,所以可能需要幾天:),但工作完美。 – 2010-05-06 11:13:25

2

當項目被通過單擊它選擇的下拉菜單沒有關閉,所以這可能是有用的:

分配的列表框中單擊事件處理程序,並添加事件處理函數

public class TestDesignProperty : UITypeEditor 
{ 

    // ... 

    IWindowsFormsEditorService editorService; 

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) 
     { 
      // ... 
      editorService = edSvc ; // so can be referenced in the click event handler 

      ListBox lb = new ListBox(); 
      lb.Click += new EventHandler(lb_Click); 
      // ... 
     } 



    void lb_Click(object sender, EventArgs e) 
    { 
     editorService.CloseDropDown(); 
    } 

}