Visual Studio设计时间属性 – 表单列表下拉菜单

[编辑]要清楚,我知道如何通过反思获得表格列表。 我更关心设计时属性网格。

我有一个用户控件具有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”命名空间中所有类型的名称。 然后,您可以在下拉列表中显示此内容,并最终实例化用户通过reflection再次选择的任何一个:

 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(); } }