我正在创建自定义控件,它将从点的列表(或数组)中绘制形状。我已经完成了基本的绘图功能,但现在我正在为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的编辑器不起作用。对于每个属性,我都会得到error Object does not match target type.

如果我将Point更改为MyPoint(具有X,Y属性的自定义类),编辑器可以正常工作,但我不想创建不需要的额外类,因为编辑器在应该工作的时候不工作。
我的问题是:我能否使用数组或点列表作为公共属性,并在设计时对其提供支持?
发布于 2016-07-25 17:23:14
您可以创建一个派生CollectionEditor的自定义集合编辑器并将typeof(List<Point>)设置为集合类型,还可以为Point注册一个新的TypeConverterAttribute
// 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; }
}发布于 2016-07-25 15:37:40
如果可以添加对PresentationCore和WindowsBase的引用,则可以使用System.Windows.Media.PointCollection
private System.Windows.Media.PointCollection _points = new System.Windows.Media.PointCollection();
public System.Windows.Media.PointCollection Points
{
get { return _points; }
set { _points = value; }
}希望这能有所帮助。
https://stackoverflow.com/questions/38561197
复制相似问题