// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993] for details. // All other rights reserved. using System.ComponentModel; using System.Globalization; namespace System.Windows.Controls { /// /// Converts a string or base value to a value. /// /// The type should be value type. /// Preview public class NullableConverter : TypeConverter where T : struct { /// /// Returns whether the type converter can convert an object from the /// specified type to the type of this converter. /// /// An object that provides a format context. /// /// The type you want to convert from. /// /// Returns true if this converter can perform the conversion; /// otherwise, false. /// public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(T)) { return true; } else if (sourceType == typeof(string)) { return true; } return false; } /// /// Returns whether the type converter can convert an object from the /// specified type to the type of this converter. /// /// An object that provides a format context. /// /// The type you want to convert to. /// /// /// Returns true if this converter can perform the conversion; /// otherwise, false. /// public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return (destinationType == typeof(T)); } /// /// Converts from the specified value to the type of this converter. /// /// An object that provides a format context. /// /// The /// to use as the /// current culture. /// The value to convert to the type of this /// converter. /// The converted value. /// /// The conversion cannot be performed. /// public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string stringValue = value as string; if (value is T) { return new Nullable((T)value); } else if (string.IsNullOrEmpty(stringValue) || String.Equals(stringValue, "Auto", StringComparison.OrdinalIgnoreCase)) { return new Nullable(); } return new Nullable((T)Convert.ChangeType(value, typeof(T), culture)); } /// /// Converts from the specified value to the a specified type from the /// type of this converter. /// /// An object that provides a format context. /// /// The /// to use as the /// current culture. /// The value to convert to the type of this /// converter. /// The type of convert the value to /// . /// The converted value. /// /// The conversion cannot be performed. /// public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value == null) { return string.Empty; } else if (destinationType == typeof(string)) { return value.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } }