1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| internal class ColorRGBConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); }
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return base.CanConvertTo(context, destinationType); }
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if(value is string strValue) { try { if(strValue.StartsWith("#")) { if (strValue.Length == 7) return new ColorRGB(byte.Parse(strValue.Substring(1,2), NumberStyles.HexNumber), byte.Parse(strValue.Substring(3,2), NumberStyles.HexNumber), byte.Parse(strValue.Substring(5,2), NumberStyles.HexNumber)); } else { string[] parts = strValue.Split(','); return new ColorRGB(byte.Parse(parts[0].Trim()), byte.Parse(parts[1].Trim()), byte.Parse(parts[2].Trim())); } } catch { throw new FormatException("格式不正确"); } } return base.ConvertFrom(context, culture, value); }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if(value is ColorRGB && destinationType == typeof(string)) return value.ToString(); return base.ConvertTo(context, culture, value, destinationType); } }
|