C# 自定义颜色编辑器在颜色结构上无法正常工作
我在这里询问了如何在属性网格中为颜色结构使用自定义颜色对话框: 如果需要,可以从该链接查看MyColorEditor类的代码。 现在我可以使用自定义颜色对话框,但前提是我使用自己的结构,在那个例子中是RGBA 如果在color struct上使用此自定义类型编辑器,则在属性网格中如下所示: 但是如果我使用我创建的RGBA结构,它看起来很正常: 出现问题的原因是UITypeEditorEditStyle.Modal未与GetEditStyle()一起应用 对于我来说,使用颜色结构比使用自定义颜色结构要好,因为这样我就可以为颜色属性设置DefaultValue,而无需编写自己的类型转换器C# 自定义颜色编辑器在颜色结构上无法正常工作,c#,colors,propertygrid,uitypeeditor,C#,Colors,Propertygrid,Uitypeeditor,我在这里询问了如何在属性网格中为颜色结构使用自定义颜色对话框: 如果需要,可以从该链接查看MyColorEditor类的代码。 现在我可以使用自定义颜色对话框,但前提是我使用自己的结构,在那个例子中是RGBA 如果在color struct上使用此自定义类型编辑器,则在属性网格中如下所示: 但是如果我使用我创建的RGBA结构,它看起来很正常: 出现问题的原因是UITypeEditorEditStyle.Modal未与GetEditStyle()一起应用 对于我来说,使用颜色结构比使用自定义
所以我的问题是如何在Color struct上使用自定义编辑器。最终找到了方法,ColorConverter导致了这个问题,所以需要像这样使用我自己的ColorConverter:
public class MyColorConverter : ColorConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return false;
}
}
编辑代码:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace HelpersLib
{
public class MyColorEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
if (value.GetType() != typeof(Color))
{
return value;
}
IWindowsFormsEditorService svc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (svc != null)
{
Color color = (Color)value;
using (DialogColor form = new DialogColor(color))
{
if (svc.ShowDialog(form) == DialogResult.OK)
{
return (Color)form.NewColor;
}
}
}
return value;
}
public override bool GetPaintValueSupported(ITypeDescriptorContext context)
{
return true;
}
public override void PaintValue(PaintValueEventArgs e)
{
Graphics g = e.Graphics;
Color color = (Color)e.Value;
if (color.A < 255)
{
using (Image checker = ImageHelpers.CreateCheckers(e.Bounds.Width / 2, e.Bounds.Height / 2, Color.LightGray, Color.White))
{
g.DrawImage(checker, e.Bounds);
}
}
using (SolidBrush brush = new SolidBrush(color))
{
e.Graphics.FillRectangle(brush, e.Bounds);
}
e.Graphics.DrawRectangleProper(Pens.Black, e.Bounds);
}
}
}
截图:
[DefaultValue(typeof(Color), "Black"),
Editor(typeof(MyColorEditor), typeof(UITypeEditor)),
TypeConverter(typeof(MyColorConverter))]
public Color Color { get; set; }