2011-08-06 26 views
7

PropertyGrid中的字符串類似Visual Studio的編輯器最簡單的方法是什麼?例如在Autos/Locals/Watches中,您可以在線預覽/編輯字符串值,但您也可以單擊放大鏡並在外部窗口中看到字符串。C#屬性網格字符串編輯器

+0

你可以做*的這部分*用自己的UITypeEditor的。 –

回答

8

你可以通過UITypeEditor來做到這一點,如下所示。在這裏,我用它在一個單獨的屬性,但IIRC你也可以顛覆所有字符串(這樣你就不需要裝飾的所有屬性):

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

static class Program 
{ 
    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 
     using(var frm = new Form { Controls = { new PropertyGrid { 
      Dock = DockStyle.Fill, SelectedObject = new Foo { Bar = "abc"}}}}) 
     { 
      Application.Run(frm); 
     } 
    } 
} 

class Foo 
{ 
    [Editor(typeof(FancyStringEditor), typeof(UITypeEditor))] 
    public string Bar { get; set; } 
} 
class FancyStringEditor : UITypeEditor 
{ 
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) 
    { 
     return UITypeEditorEditStyle.Modal; 
    } 
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) 
    { 
     var svc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); 
     if (svc != null) 
     { 
      using (var frm = new Form { Text = "Your editor here"}) 
      using (var txt = new TextBox { Text = (string)value, Dock = DockStyle.Fill, Multiline = true }) 
      using (var ok = new Button { Text = "OK", Dock = DockStyle.Bottom }) 
      { 
       frm.Controls.Add(txt); 
       frm.Controls.Add(ok); 
       frm.AcceptButton = ok; 
       ok.DialogResult = DialogResult.OK; 
       if (svc.ShowDialog(frm) == DialogResult.OK) 
       { 
        value = txt.Text; 
       } 
      } 
     } 
     return value; 
    } 
} 

要爲所有應用此字符串成員:代替將[Editor(...)],適用於應用程序的早期某處如下:

TypeDescriptor.AddAttributes(typeof(string), new EditorAttribute(
    typeof(FancyStringEditor), typeof(UITypeEditor))); 
+0

我實際上應該低估你的答案,因爲它鼓勵我採取偷懶的方式,只是複製和粘貼你的代碼。 ;) – John

+0

是的這段代碼是完美的,簡單的,馬上就可以工作。謝謝 – IEnumerable