using System; using System.ComponentModel; namespace Revit.SDK.Samples.ProjectInfo.CS { /// /// Converts angle with string /// public class AngleConverter : TypeConverter { #region Methods /// /// Converts from string. /// /// Converted string public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } /// /// Converts to string. /// /// Converted string public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType.Equals(typeof(string)) || base.CanConvertTo(context, destinationType); } /// /// Converts from string. /// /// An System.ComponentModel.ITypeDescriptorContext /// that provides a format context. /// An optional System.Globalization.CultureInfo. /// If not supplied, the current culture is assumed. /// string to be converted to an element /// An element if the element exists, otherwise null public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string text = value as string; if (!string.IsNullOrEmpty(text)) { return AngleString2Double(text); } return base.ConvertFrom(context, culture, value); } /// /// Converts to string. /// /// An ITypeDescriptorContext that provides a format context. /// A CultureInfo. If null is passed, the current culture is assumed. /// The Object to convert. /// The Type to convert the value parameter to. /// Converted string public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(string)) { if (value == null) return string.Empty; double angle = (double) value; return Double2AngleString(angle); } return base.ConvertTo(context, culture, value, destinationType); } /// /// Convert angle string to double value /// /// Angle string /// Double value private static double AngleString2Double(string value) { int n = value.Length - 1; if (!char.IsDigit(value[n])) { value = value.Substring(0, n); } return Double.Parse(value) * 0.0174532925199433; } /// /// Convert double value to angle string /// /// Angle value /// Angle string, the unit is degree. private static string Double2AngleString(Double value) { // 0xb0 is ASCII for unit flag of "degree" return ((object)Math.Round(value / 0.0174532925199433, 3)).ToString() + (char)0xb0; } #endregion } }