82 lines
3.1 KiB
C#
82 lines
3.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.ComponentModel;
|
|
using System.Globalization;
|
|
using UnitsNet;
|
|
using UnitsNet.Units;
|
|
|
|
namespace CaeGlobals
|
|
{
|
|
public class StringLengthPixelConverter : TypeConverter
|
|
{
|
|
// Variables
|
|
protected static string pixelAbbreviation = "px";
|
|
protected static string error = "Unable to parse quantity. Expected the form \"{value} {unit abbreviation}" +
|
|
"\", such as \"5.5 m\". The spacing is optional.";
|
|
|
|
|
|
// Properties
|
|
|
|
|
|
// Constructors
|
|
public StringLengthPixelConverter()
|
|
{
|
|
}
|
|
|
|
|
|
// Methods
|
|
public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType)
|
|
{
|
|
if (sourceType == typeof(string)) return true;
|
|
else return base.CanConvertFrom(context, sourceType);
|
|
}
|
|
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
|
|
{
|
|
// Convert from string
|
|
if (value is string valueString) return (int)MyNCalc.ConvertFromString(valueString, ConvertToCurrentUnits);
|
|
else return base.ConvertFrom(context, culture, value);
|
|
}
|
|
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
|
|
{
|
|
// Convert to string
|
|
try
|
|
{
|
|
if (destinationType == typeof(string))
|
|
{
|
|
if (value is int valueInt)
|
|
{
|
|
return valueInt.ToString() + " " + pixelAbbreviation;
|
|
}
|
|
}
|
|
return base.ConvertTo(context, culture, value, destinationType);
|
|
}
|
|
catch
|
|
{
|
|
return base.ConvertTo(context, culture, value, destinationType);
|
|
}
|
|
}
|
|
//
|
|
public static double ConvertToCurrentUnits(string valueWithUnitString)
|
|
{
|
|
try
|
|
{
|
|
valueWithUnitString = valueWithUnitString.Replace(pixelAbbreviation, "");
|
|
return int.Parse(valueWithUnitString);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw new Exception(error + Environment.NewLine + Environment.NewLine + SupportedUnitAbbreviations());
|
|
}
|
|
}
|
|
public static string SupportedUnitAbbreviations()
|
|
{
|
|
string supportedUnitAbbreviations = "Supported pixel abbreviations: " + pixelAbbreviation + ".";
|
|
return supportedUnitAbbreviations;
|
|
}
|
|
}
|
|
|
|
} |