简体   繁体   中英

How to custom draw a GridItem in PropertyGrid?

I want to draw the Property value in my PropertyGrid in a similar fashion as owner-drawing items in a ListView (Details), and other controls.

If a Property is declared of type Color, its value is drawn with a swatch of the color next to a string description. If a Property is a type of Image, a thumbnail of the image is drawn next to a string description.

I have a property that is a class that contains three Properties of type Color. I want to draw all three colors in the PropertyGrid next to the Property name. The class has an ExpandableObjectConverter as the TypeConverter, where the colors are edited, but the only option I know of for changing how the Property's value is displayed is to use a TypeConverter to return a String.

You need to create a editor for your type (which has 3 color properties) by deriving from UITypeEditor and overriding its GetPaintValueSupported and PaintValue . Than register the editor for your class using an Editor attribute:

在此处输入图像描述

Exapmle

using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
public class MyComponent : Component
{
    public SampleClass SampleProperty { get; set; } = new SampleClass();
}
[TypeConverter(typeof(ExpandableObjectConverter))]
[Editor(typeof(SampleClassEditor), typeof(UITypeEditor))]
public class SampleClass
{
    public Color Color1 { get; set; } = Color.Red;
    public Color Color2 { get; set; } = Color.Green;
    public Color Color3 { get; set; } = Color.Blue;
}
public class SampleClassEditor : UITypeEditor
{
    public override bool GetPaintValueSupported(ITypeDescriptorContext context)
    {
        return true;
    }
    public override void PaintValue(PaintValueEventArgs e)
    {
        var sample = e.Value as SampleClass;
        if (sample != null)
        {
            int x = e.Bounds.X, y = e.Bounds.Y;
            int w = e.Bounds.Width, h = e.Bounds.Height;
            using (var b = new SolidBrush(sample.Color1))
                e.Graphics.FillRectangle(b, x, y, w / 3, h);
            using (var b = new SolidBrush(sample.Color2))
                e.Graphics.FillRectangle(b, x += w / 3, y, w / 3, h);
            using (var b = new SolidBrush(sample.Color3))
                e.Graphics.FillRectangle(b, x += w / 3, y, w / 3 + 1, h);
        }
        base.PaintValue(e);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM