C#属性网格字符串编辑器

时间:2011-08-06 21:24:54

标签: c# winforms

在PropertyGrid中使用类似Visual Studio的编辑器的最简单方法是什么?例如,在Autos / Locals / Watches中,您可以在线预览/编辑字符串值,但您也可以单击放大镜并在外部窗口中查看字符串。

1 个答案:

答案 0 :(得分: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)));