Type 类型为 属性 的用户控件

UserControl with property of type Type

我正在使用 Type 类型的 属性 实现 UserControl

public partial class MyUserControl: UserControl
{
    public MyUserControl()
    {
        InitializeComponent();
    }

    public Type PluginType { get; set; } = typeof(IPlugin);
}

在表单上放置 MyUserControl 时,我可以在设计器中看到 PluginType 属性,但我无法编辑它。

如何使这个 属性 可编辑?理想情况下,设计师会显示一个编辑器,我可以在其中选择我的程序集(或任何程序集)中的一种类型。有这样的编辑器吗?

使用 Editor 属性告诉 class 将用于编辑 属性:

[Editor("Mynamespace.TypeSelector , System.Design", typeof(UITypeEditor)), Localizable(true)]
public Type PluginType { get; set; }

定义一个TypeSelectorclass:

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,您可以在其中 select 一个类型并将其分配给 Value 属性。在这里,您可以使用反射来过滤实现 IPlugin 的程序集中的类型。