我正在使用一个属性网格,使用这里找到的适配器使用字典.
我现在需要能够使用自定义编辑器.更具体地说是文件选择器.如果字典中的对象是字符串,则它只使用默认的字符串编辑器.
我可以实现一个名为FilePath的新类,或者只是作为字符串包装器的东西,但会导致属性网格使用OpenFileDialog,并在选择后将结果显示为PropertyGrid中的字符串吗?
这可能吗?如果是这样怎么样?
如果你想使用你引用的字典适配器在属性网格中使用文件路径编辑器,我会按照你的建议制作FilePath类.您还需要实现另外两个类,以使所有这些都与属性网格一起使用:编辑器和类型转换器.
我们假设您的FilePath对象很简单:
class FilePath
{
public FilePath(string inPath)
{
Path = inPath;
}
public string Path { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您的属性网格将以浅灰色显示类名,不是很有用.让我们编写一个TypeConverter来显示这个类真正包含的字符串
class FilePathConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (IsValid(context, value))
return new FilePath((string)value);
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return destinationType == typeof(string);
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
return ((FilePath)value).Path;
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool IsValid(ITypeDescriptorContext context, object value)
{
if (value.GetType() == typeof(string))
return true;
return base.IsValid(context, value);
}
}
Run Code Online (Sandbox Code Playgroud)
将TypeConverter属性添加到我们的FilePath类以转换为字符串和从字符串转换.
[TypeConverter(typeof(FilePathConverter))]
class FilePath
{
...
}
Run Code Online (Sandbox Code Playgroud)
现在属性网格将显示字符串而不是类型名称,但是您希望省略号显示文件选择对话框,因此我们创建了一个UITypeEditor:
class FilePathEditor : UITypeEditor
{
public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return System.Drawing.Design.UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
FilePath path = (FilePath)value;
OpenFileDialog openFile = new OpenFileDialog();
openFile.FileName = path.Path;
if (openFile.ShowDialog() == DialogResult.OK)
path.Path = openFile.FileName;
return path;
}
}
Run Code Online (Sandbox Code Playgroud)
将Editor属性添加到我们的FilePath类以使用新类:
[TypeConverter(typeof(FilePathConverter))]
[Editor(typeof(FilePathEditor), typeof(UITypeEditor))]
class FilePath
{
...
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以将FilePath对象添加到IDictionary,并通过属性网格对其进行编辑
IDictionary d = new Dictionary<string, object>();
d["Path"] = new FilePath("C:/");
Run Code Online (Sandbox Code Playgroud)