Dus*_*oks 5 c# design-time properties visual-studio winforms
[编辑]要清楚,我知道如何通过反思获得表格列表.我更关心设计时属性网格.
我有一个用户控件具有Form类型的公共属性.
我希望能够在设计时从下拉菜单中选择一个表单.
我想从set命名空间填充表单下拉列表:UI.Foo.Forms
如果您拥有Control的公共属性,这将起作用.在设计时,属性将自动使用表单上的所有控件填充下拉列表,供您选择.我只想用命名空间中的所有表单填充它.
我该怎么做呢?我希望我足够清楚,所以没有混乱.如果可能的话,我正在寻找一些代码示例.当我有其他截止日期要求时,我试图避免花太多时间在这上面.
感谢您的帮助.
您可以通过Reflection轻松获取课程:
var formNames = this.GetType().Assembly.GetTypes().Where(x => x.Namespace == "UI.Foo.Forms").Select(x => x.Name);
Run Code Online (Sandbox Code Playgroud)
假设您从与表单相同的程序集中的代码中调用它,您将获得"UI.Foo.Forms"命名空间中所有类型的名称.然后,您可以在下拉列表中显示此内容,并最终实例化用户通过反射再次选择的任何一个:
Activator.CreateInstance(this.GetType("UI.Form.Forms.FormClassName"));
Run Code Online (Sandbox Code Playgroud)
[编辑]添加设计时代码的代码:
在您的控件上,您可以创建一个Form属性:
[Browsable(true)]
[Editor(typeof(TestDesignProperty), typeof(UITypeEditor))]
[DefaultValue(null)]
public Type FormType { get; set; }
Run Code Online (Sandbox Code Playgroud)
其中引用了必须定义的编辑器类型.代码非常不言自明,只需要进行少量调整,您就可以完全按照自己的意愿生成代码.
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;
}
}
Run Code Online (Sandbox Code Playgroud)