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

本文关键字:编辑器 字符串 网格 属性 | 更新日期: 2023-09-27 18:04:37

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

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

您可以通过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)));