UserControl with property of type Type

妖精的绣舞 提交于 2019-12-11 02:36:09

问题


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

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?


回答1:


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

Define a TypeSelector class:

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

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.



来源:https://stackoverflow.com/questions/35749135/usercontrol-with-property-of-type-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!