属性类型为“类型的用户控件”

本文关键字:类型 控件 用户 属性 | 更新日期: 2023-09-27 18:37:05

我正在实现一个具有 Type 类型的属性的UserControl

public partial class MyUserControl: UserControl
{
    public MyUserControl()
    {
        InitializeComponent();
    }
    public Type PluginType { get; set; } = typeof(IPlugin);
}

在窗体上放置MyUserControl时,我可以在设计器中看到 PluginType 属性,但无法对其进行编辑。

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

属性类型为“类型的用户控件”

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

[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 的程序集中的类型。