VS 属性编辑器问题
我做了个自定义控件,里面有一个List<Point>的属性。
可是将它拖到窗体中后,无法在编辑器里面修改属性的值。
List<Point>中可以添加删除点,但每个Point的X和Y的值都无法改变,编辑器显示“对象与目标类型不匹配”。如图:
网上找了很久,问题原因好像是由于Point属于struct,没法直接在List<>里面修改元素的成员。
比如一个集合List<Point> points;points[0].X=10;就会出现错误“无法修改“System.Collections.Generic.List<System.Drawing.Point>.this[int]”的返回值,因为它不是变量”
最后找到官网上:https://connect.microsoft.com/VisualStudio/feedback/details/552326/collectioneditor-cannot-be-used-with-list-point#tabs,[b]一位老外反馈了这个问题,但没有解决办法…………我只知道似乎可以给属性设置自定义的TypeCoverter来解决,但对这个东西不了解,网上搜的方法试了半天没弄清楚,求高人指教了![/b]
------解决方案--------------------using System;
using System.ComponentModel;
using System.Globalization;
using System.Drawing;
public class PointConverter : TypeConverter {
// Overrides the CanConvertFrom method of TypeConverter.
// The ITypeDescriptorContext interface provides the context for the
// conversion. Typically, this interface is used at design time to
// provide information about the design-time container.
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
// Overrides the ConvertFrom method of TypeConverter.
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value) {
if (value is string) {
string[] v = ((string)value).Split(new char[] {','});
return new Point(int.Parse(v[0]), int.Parse(v[1]));
}
return base.ConvertFrom(context, culture, value);
}
// Overrides the ConvertTo method of TypeConverter.
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType) {
if (destinationType == typeof(string)) {
return ((Point)value).X + "," + ((Point)value).Y;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
------解决方案--------------------不错不错,有水平
------解决方案--------------------http://topic.csdn.net/u/20111002/12/bcc5a9a4-dc3d-46cb-9e97-165006c4f7e1.html
------解决方案--------------------集合应该是用类似如下 collection editor 去编辑
// ContactCollectionEditor.cs
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;
namespace Samples.AspNet.CS.Controls
{
public class ContactCollectionEditor : CollectionEditor
{
public ContactCollectionEditor(Type type)
: base(type)
{
}
protected override bool CanSelectMultipleInstances()
{
return false;
}
protected override Type CreateCollectionItemType()
{
return typeof(Contact);
}
}
}