Example #1
0
        /// <inheritdoc />
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!this.initialized)
            {
                this.Initialize();
            }

            var message = this.errorText.ToString();

            if (!(targetType == typeof(Resistance) || targetType == typeof(Resistance?)))
            {
                message += $"{this.GetType().Name} does not support converting to {targetType.Name}";
            }

            if (message != string.Empty)
            {
                message = message.TrimEnd('\r', '\n');
                if (Is.DesignMode)
                {
                    throw new InvalidOperationException(message);
                }

                return(message);
            }

            if (value == null)
            {
                return(null);
            }

            if (value is double)
            {
                return(new Resistance((double)value, this.unit.Value));
            }

            var text = value as string;

            if (string.IsNullOrEmpty(text))
            {
                return(null);
            }

            var unitInput = this.UnitInput ?? Wpf.UnitInput.ScalarOnly;

            switch (unitInput)
            {
            case Wpf.UnitInput.ScalarOnly:
            {
                double d;
                if (double.TryParse(text, NumberStyles.Float, culture, out d))
                {
                    return(new Resistance(d, this.unit.Value));
                }

                Resistance result;
                if (Resistance.TryParse(text, NumberStyles.Float, culture, out result))
                {
                    return($"#{text}#");        // returning modified text so that TypeConverter fails and we get an error
                }

                return(text);        // returning raw to trigger error
            }

            case Wpf.UnitInput.SymbolAllowed:
            {
                double d;
                int    pos = 0;
                WhiteSpaceReader.TryRead(text, ref pos);
                if (DoubleReader.TryRead(text, ref pos, NumberStyles.Float, culture, out d))
                {
                    WhiteSpaceReader.TryRead(text, ref pos);
                    if (pos == text.Length)
                    {
                        return(new Resistance(d, this.unit.Value));
                    }
                }

                goto case Wpf.UnitInput.SymbolRequired;
            }

            case Wpf.UnitInput.SymbolRequired:
            {
                Resistance result;
                if (Resistance.TryParse(text, NumberStyles.Float, culture, out result))
                {
                    return(result);
                }

                return(text);
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }