Point
您可以使用以下代码将属性添加到允许在控件的属性网格中进行编辑的类型的自定义控件:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible),
EditorBrowsable(EditorBrowsableState.Advanced),
TypeConverter(typeof(PointConverter))]
public Point MyPointProperty { get; set; }
如果您尝试使用 a 相同的方法,SizeF
您会发现 .NET 中没有内置TypeConverter
的PointF
. 不过,您可以创建自己的,我在这里找到了一个(并复制并粘贴了下面的大部分代码)。
使用 aPointF
TypeConverter
您可以编写PointF
可在属性窗口中编辑的类型的属性:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible),
EditorBrowsable(EditorBrowsableState.Advanced),
TypeConverter(typeof(PointFConverter))]
public PointF MyPointFProperty { get; set; }
这是在上面链接的文章中找到的 PointF 类型转换器代码:
/// <summary>
/// PointFConverter
/// </summary>
public class PointFConverter : ExpandableObjectConverter
{
/// <summary>
/// Creates a new instance of PointFConverter
/// </summary>
public PointFConverter() {
}
/// <summary>
/// Boolean, true if the source type is a string
/// </summary>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) return true;
return base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// Converts the specified string into a PointF
/// </summary>
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
if (value is string) {
try {
string s = (string)value;
string[] converterParts = s.Split(',');
float x = 0;
float y = 0;
if (converterParts.Length > 1) {
x = float.Parse(converterParts[0].Trim());
y = float.Parse(converterParts[1].Trim());
} else if (converterParts.Length == 1) {
x = float.Parse(converterParts[0].Trim());
y = 0;
} else {
x = 0F;
y = 0F;
}
return new PointF(x, y);
} catch {
throw new ArgumentException("Cannot convert [" + value.ToString() + "] to pointF");
}
}
return base.ConvertFrom(context, culture, value);
}
/// <summary>
/// Converts the PointF into a string
/// </summary>
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
if (destinationType == typeof(string)) {
if (value.GetType() == typeof(PointF)) {
PointF pt = (PointF)value;
return string.Format("{0}, {1}", pt.X, pt.Y);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
}