Beispiel #1
0
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture. </param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert. </param>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string @string = value as string;

            if (@string != null)
            {
                Period period;
                if (TimeHelpers.GetPeriodPatterns(culture).TryParseAny(@string.Trim(), out period))
                {
                    return(period);
                }

                TimeSpan timeSpan;
                if (TimeSpan.TryParse(@string, out timeSpan))
                {
                    // ReSharper disable once PossibleNullReferenceException
                    return(Period.FromTicks(timeSpan.Ticks).Normalize());
                }

                throw new NotSupportedException(
                          // ReSharper disable once AssignNullToNotNullAttribute
                          string.Format(Resources.PeriodConverter_ConvertFrom_CannotParse, @string));
            }
            if (value is TimeSpan)
            {
                TimeSpan timeSpan = (TimeSpan)value;
                // ReSharper disable once PossibleNullReferenceException
                return(Period.FromTicks(timeSpan.Ticks).Normalize());
            }
            if (value is Duration)
            {
                Duration duration = (Duration)value;
                // ReSharper disable once PossibleNullReferenceException
                return(Period.FromTicks(duration.Ticks).Normalize());
            }

            return(base.ConvertFrom(context, culture, value));
        }