问题
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