2016-03-02 43 views
2

我正在實施UserControl,屬性類型爲TypeUserControl屬性類型爲

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

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

當窗體上放置MyUserControl我可以看到在設計師的PluginType屬性,但我不能編輯它。

如何讓此屬性可編輯?理想情況下,設計師會向我展示一個編輯器,我可以在其中選擇我的裝配(或任何裝配)中的一種類型。有這樣一位編輯嗎?

+1

爲什麼downvote? –

回答

2

使用Editor屬性告訴至極類將被用於屬性編輯:

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