具有 Type 类型属性的 UserControl [英] UserControl with property of type Type
问题描述
我正在使用 Type
类型的属性实现一个 UserControl
.
I'm implementing a UserControl
with a property of type Type
.
public partial class MyUserControl: UserControl
{
public MyUserControl()
{
InitializeComponent();
}
public Type PluginType { get; set; } = typeof(IPlugin);
}
在表单上放置 MyUserControl
时,我可以在设计器中看到 PluginType
属性,但我无法对其进行编辑.
When placing MyUserControl
on a form I can see the PluginType
property in the designer, but I cannot edit it.
如何使该属性可编辑?理想情况下,设计师会显示一个编辑器,我可以在其中选择我的程序集(或任何程序集)中的一种类型.有这样的编辑器吗?
How can I make this property editable? Ideally the designer would show an editor where I can pick one of the types in my assembly (or any assembly). Is there such an editor?
推荐答案
使用 Editor
属性告诉哪个类将用于编辑属性:
Use Editor
attribute telling wich class will be used for editing of property:
[Editor("Mynamespace.TypeSelector , System.Design", typeof(UITypeEditor)), Localizable(true)]
public Type PluginType { get; set; }
定义一个 TypeSelector
类:
public class TypeSelector : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
if (context == null || context.Instance == null)
return base.GetEditStyle(context);
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
IWindowsFormsEditorService editorService;
if (context == null || context.Instance == null || provider == null)
return value;
editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
FormTypeSelector dlg = new FormTypeSelector();
dlg.Value = value;
dlg.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
if (editorService.ShowDialog(dlg) == System.Windows.Forms.DialogResult.OK)
{
return dlg.Value;
}
return value;
}
}
剩下的就是实现FormTypeSelector
,您可以在其中选择一个类型并将其分配给Value
属性.在这里,您可以使用反射来过滤实现 IPlugin 的程序集中的类型.
Only thing remaining is to implement FormTypeSelector
in which you can select a type and assign it to Value
property. Here you can use reflection to filter the types in an assembly wich implements IPlugin.
这篇关于具有 Type 类型属性的 UserControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!