我正在创建自定义控件,它将从列表(或数组)中绘制形状。 我已经完成了基本的绘图功能,但现在我在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.
如果我将Point
更改为MyPoint
(具有X,Y属性的自定义类)编辑器工作正常,但我不想创建不需要的额外类,因为编辑器不起作用时应该。
我的问题是:我可以使用数组或点列表作为公共属性并获得设计时支持吗?
答案 0 :(得分:2)
答案 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; }
}