【发布时间】:2011-08-06 21:24:54
【问题描述】:
在 PropertyGrid 中使用类似 Visual Studio 的字符串编辑器的最简单方法是什么?例如,在 Autos/Locals/Watches 中,您可以在线预览/编辑字符串值,但您也可以单击放大镜并在外部窗口中查看字符串。
【问题讨论】:
-
你可以用你自己的 UITypeEditor 来做一些。
在 PropertyGrid 中使用类似 Visual Studio 的字符串编辑器的最简单方法是什么?例如,在 Autos/Locals/Watches 中,您可以在线预览/编辑字符串值,但您也可以单击放大镜并在外部窗口中查看字符串。
【问题讨论】:
您可以通过UITypeEditor 执行此操作,如下所示。这里我在单个属性上使用它,但是 IIRC 你也可以颠覆 all 字符串(这样你就不需要装饰所有属性):
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)));
【讨论】: