无法在设计时编辑Point []或List <point>

时间:2016-07-25 06:41:34

标签: c# winforms user-controls windows-forms-designer design-time

我正在创建自定义控件,它将从列表(或数组)中绘制形状。 我已经完成了基本的绘图功能,但现在我在Visual Studio中挣扎于设计时支持。

我创建了两个属性:

private Point _point;
public Point Point
{
    get { return _point; }
    set { _point = value; }
}

private Point[] _points;
public Point[] Points
{
    get { return _points; }
    set { _points = value; }
}

如下面屏幕上显示的Point是可编辑的,但Points的编辑器无法正常工作。对于每个属性,我收到错误Object does not match target type.

enter image description here

如果我将Point更改为MyPoint(具有X,Y属性的自定义类)编辑器工作正常,但我不想创建不需要的额外类,因为编辑器不起作用时应该。

我的问题是:我可以使用数组或点列表作为公共属性并获得设计时支持吗?

2 个答案:

答案 0 :(得分:2)

如果您可以添加对getText()PresentationCore的引用,则可以使用sourcecode

WindowsBase

希望可以提供帮助。

答案 1 :(得分:2)

您可以创建一个自定义集合编辑器,派生CollectionEditor并将typeof(List<Point>)设置为集合类型,同时为TypeConverterAttribute注册一个新的Point

// Add reference to System.Design
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.ComponentModel.Design;

public class MyPointCollectionEditor : CollectionEditor
{
    public MyPointCollectionEditor() : base(typeof(List<Point>)) { }
    public override object EditValue(ITypeDescriptorContext context,
        IServiceProvider provider, object value)
    {
        TypeDescriptor.AddAttributes(typeof(Point), 
            new Attribute[] { new TypeConverterAttribute() });
        var result = base.EditValue(context, provider, value);
        TypeDescriptor.AddAttributes(typeof(Point), 
            new Attribute[] { new TypeConverterAttribute(typeof(PointConverter)) });
        return result;
    }
}

然后将其注册为List<Point>的编辑:

using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;

public class MyClass : Component
{
    public MyClass() { Points = new List<Point>(); }

    [Editor(typeof(MyPointCollectionEditor), typeof(UITypeEditor))]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public List<Point> Points { get; private set; }
}