在PropertyGrid中使用自定义颜色选择器对话框

在PropertyGrid中, 默认颜色选择器对话框不允许设置颜色的alpha值。

我已经创建了自己的颜色选择器对话框,并希望在PropertyGrid中使用它,但不知道如何做到这一点。

我设法在属性网格中使用我的自定义颜色选择器对话框并在此处复制它的代码以防有些人也需要它:

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(RGBA)) { return value; } IWindowsFormsEditorService svc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (svc != null) { using (DialogColor form = new DialogColor((RGBA)value)) { if (svc.ShowDialog(form) == DialogResult.OK) { return form.NewColor.RGBA; } } } return value; } public override bool GetPaintValueSupported(ITypeDescriptorContext context) { return true; } public override void PaintValue(PaintValueEventArgs e) { using (SolidBrush brush = new SolidBrush((RGBA)e.Value)) { e.Graphics.FillRectangle(brush, e.Bounds); } e.Graphics.DrawRectangleProper(Pens.Black, e.Bounds); } } } 

这就是它在物业网格中的表现:

screenshot1

当我点击它的按钮时,它将打开自定义颜色对话框 。

但仍然有一个我无法解决的问题。 我不能在这个UITypeEditor中使用Color struct,因此创建了RGBA类。 当我使用颜色结构时,它看起来像这样:

screenshot2

我想为此我打开另一个问题: Custom ColorEditor在Color struct上无法正常工作

要与PropertyGrid进行交互,您必须创建自己的“属性类”( 如此处所述 )。 您可以自定义不同的部件,因此可以根据需要提供多种解决方案。 作为问题的第一种方法,这里有一个propertyGrid1的代码:

 Property curProperty = new Property(); propertyGrid1.SelectedObject = curProperty; 

Property的定义如下:

 public class Property { private ColorDialog _dialog = new customColorDialogDialog(); public ColorDialog dialog { get { return _dialog; } set { _dialog.ShowDialog(); } } } class customColorDialogDialog : ColorDialog { } 

在此代码中,单击属性名称右侧的单元格(“对话框”)时会触发颜色对话框( customColorDialogDialog )。