如何获取此图像的文件路径?另外,有什么办法可以覆盖弹出的对话框并放入我自己的对话框?
要实现这两种方式,那就是创建一个新的UITypeEditor
:
public class BitmapLocationEditor : UITypeEditor
{
}
我覆盖了、GetEditStyle
和EditValue
方法。GetPaintvalueSupported
PaintValue
// Displays an ellipsis (...) button to start a modal dialog box
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
// Edits the value of the specified object using the editor style indicated by the GetEditStyle method.
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
// Show the dialog we use to open the file.
// You could use a custom one at this point to provide the file path and the image.
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Image files (*.bmp | *.bmp;";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
Bitmap bitmap = new Bitmap(openFileDialog.FileName);
bitmap.SetPath(openFileDialog.FileName);
return bitmap;
}
}
return value;
}
// Indicates whether the specified context supports painting
// a representation of an object's value within the specified context.
public override bool GetPaintValueSupported(ITypeDescriptorContext context)
{
return true;
}
// Paints a representation of the value of an object using the specified PaintValueEventArgs.
public override void PaintValue(PaintValueEventArgs e)
{
if (e.Value != null)
{
// Get image
Bitmap bmp = (Bitmap)e.Value;
// This rectangle indicates the area of the Properties window to draw a representation of the value within.
Rectangle destRect = e.Bounds;
// Optional to set the default transparent color transparent for this image.
bmp.MakeTransparent();
// Draw image
e.Graphics.DrawImage(bmp, destRect);
}
}
你的Obj
类应该保持不变,除了添加一个属性来利用我们的新BitmapLocationEditor
类:
public class Obj
{
private Bitmap myImage;
[Category("Main Category")]
[Description("Your favorite image")]
[Editor(typeof(BitmapLocationEditor), typeof(UITypeEditor))]
public Bitmap MyImage
{
get { return myImage; }
set
{
myImage = value;
}
}
}
SetPath
方法中使用的方法EditValue
只是设置Bitmap.Tag
属性的扩展方法。您可以稍后使用该GetPath
方法来检索图像文件的实际路径。
public static class BitmapExtension
{
public static void SetPath(this Bitmap bitmap, string path)
{
bitmap.Tag = path;
}
public static string GetPath(this Bitmap bitmap)
{
return bitmap.Tag as string;
}
}
关于 PropertyGrid 的文章