2009-06-19 52 views
26

我有一個列表<>(我的自定義類)。我想在PropertyGrid控件的一個框中顯示此列表中的特定項目。在框的結尾,我想要[...]按鈕。點擊後,它將打開一個表格,除其他外,它將允許他們從列表中選擇一個項目。關閉時,PropertyGrid會更新以反映選定的值。如何創建打開表單的自定義PropertyGrid編輯器項目?

任何幫助表示讚賞。

回答

60

你需要實現一個模式UITypeEditor,使用IWindowsFormsEditorService服務以顯示它:

using System.ComponentModel; 
using System.Drawing.Design; 
using System.Windows.Forms; 
using System.Windows.Forms.Design; 
using System; 

class MyType 
{ 
    private Foo foo = new Foo(); 
    public Foo Foo { get { return foo; } } 
} 

[Editor(typeof(FooEditor), typeof(UITypeEditor))] 
[TypeConverter(typeof(ExpandableObjectConverter))] 
class Foo 
{ 
    private string bar; 
    public string Bar 
    { 
     get { return bar; } 
     set { bar = value; } 
    } 
} 
class FooEditor : UITypeEditor 
{ 
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) 
    { 
     return UITypeEditorEditStyle.Modal; 
    } 
    public override object EditValue(ITypeDescriptorContext context, System.IServiceProvider provider, object value) 
    { 
     IWindowsFormsEditorService svc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; 
     Foo foo = value as Foo; 
     if (svc != null && foo != null) 
     {    
      using (FooForm form = new FooForm()) 
      { 
       form.Value = foo.Bar; 
       if (svc.ShowDialog(form) == DialogResult.OK) 
       { 
        foo.Bar = form.Value; // update object 
       } 
      } 
     } 
     return value; // can also replace the wrapper object here 
    } 
} 
class FooForm : Form 
{ 
    private TextBox textbox; 
    private Button okButton; 
    public FooForm() { 
     textbox = new TextBox(); 
     Controls.Add(textbox); 
     okButton = new Button(); 
     okButton.Text = "OK"; 
     okButton.Dock = DockStyle.Bottom; 
     okButton.DialogResult = DialogResult.OK; 
     Controls.Add(okButton); 
    } 
    public string Value 
    { 
     get { return textbox.Text; } 
     set { textbox.Text = value; } 
    } 
} 
static class Program 
{ 
    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Form form = new Form(); 
     PropertyGrid grid = new PropertyGrid(); 
     grid.Dock = DockStyle.Fill; 
     form.Controls.Add(grid); 
     grid.SelectedObject = new MyType(); 
     Application.Run(form); 
    } 
} 

注:如果您需要訪問有關財產(父對象等)的情況下的東西,這是什麼ITypeDescriptorContext(在EditValue)提供;它會告訴您所涉及的PropertyDescriptorInstanceMyType)。

+3

我希望我能+1這兩次!我在近兩年前就提出了這個建議,並且我在另一個項目上又回到了同樣的問題,並且仍然發現它正是我所需要的。很好的答案,謝謝! – Paccc 2013-01-06 03:22:44

相關問題