为什么要使用自定义编辑器?如果您只想要一个对象上的字符串属性,那么 Marc Gravell 的答案有效。
但是,如果属性网格中对象的“文件”属性是自定义类,您还需要实现自定义类型转换器。
例如:
namespace WindowsFormsApplication
{
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Globalization;
using System.Windows.Forms;
using System.Windows.Forms.Design;
class MyEditor : FileNameEditor
{
public override bool GetPaintValueSupported(ITypeDescriptorContext context)
{
return false;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
string s = Environment.CurrentDirectory;
object e = base.EditValue(context, provider, value);
Environment.CurrentDirectory = s;
var myFile = value as MyFile;
if (myFile != null && e is string)
{
myFile.FileName = (string)e;
return myFile;
}
return e;
}
}
class MyFileTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
return new MyFile { FileName = (string)value };
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var myFile = value as MyFile;
if (myFile != null && destinationType == typeof(string))
return myFile.FileName;
return base.ConvertTo(context, culture, value, destinationType);
}
}
[TypeConverter(typeof(MyFileTypeConverter))]
[Editor(typeof(MyEditor), typeof(UITypeEditor))]
class MyFile
{
public string FileName { get; set; }
}
class MyFileContainer
{
public MyFileContainer()
{
File1 = new MyFile { FileName = "myFile1.txt" };
File2 = new MyFile { FileName = "myFile2.txt" };
}
public MyFile File1 { get; set; }
public MyFile File2 { get; set; }
}
static public class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var f = new Form())
using (var pg = new PropertyGrid())
{
pg.Dock = DockStyle.Fill;
pg.SelectedObject = new MyFileContainer();
f.Controls.Add(pg);
Application.Run(f);
}
}
}
}
为了支持就地编辑文件名并剪切和粘贴 PropertyGrid 需要知道如何从字符串转换为“文件”类型并再次转换回来。如果您没有在 TypeConverter 中实现转换为字符串的方法,该属性将显示对象的 ToString() 的结果。
我建议拿出 Reflector.Net 并阅读 BCL 中的一些 UITypeEditors 和 TypeConverters 的源代码,因为它可以非常有用地了解 Microsoft 如何支持在属性网格中编辑 Color、TimeSpan、DateTime 等。
此外,请小心打开文件对话框。如果您不小心,标准的 WinForms 打开文件对话框可能会更改您的应用程序当前工作目录。我不认为 FileNameEditor 有这个问题,但我只在 Windows 7 下测试过。