![](/img/trans.png)
[英]How to list all instances of a component of typeX on a form in a drop down of a control property in design time
[英]Visual Studio Design Time Property - Form List Drop Down
[編輯]要清楚,我知道如何通過反思獲得表格列表。 我更關心設計時屬性網格。
我有一個用戶控件具有Form類型的公共屬性。
我希望能夠在設計時從下拉菜單中選擇一個表單。
我想從set命名空間填充表單下拉列表:UI.Foo.Forms
如果您擁有Control的公共屬性,這將起作用。 在設計時,屬性將自動使用表單上的所有控件填充下拉列表,供您選擇。 我只想用命名空間中的所有表單填充它。
我該怎么做呢? 我希望我足夠清楚,所以沒有混亂。 如果可能的話,我正在尋找一些代碼示例。 當我有其他截止日期要求時,我試圖避免花太多時間在這上面。
感謝您的幫助。
您可以通過Reflection輕松獲取課程:
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;
}
}
通過單擊選擇項目時,下拉列表不會關閉,因此這可能很有用:
為列表框分配click事件處理程序並添加事件處理函數
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.