using System;
using System.ComponentModel;
using System.Globalization;
using System.ComponentModel.Design;
namespace BLToolkit.ComponentModel
{
///
/// Converts the value of an object into a .
///
public class TypeTypeConverter: TypeConverter
{
// Human readable text for 'nothing selected'.
//
private const string NoType = "(none)";
///
/// Returns whether this converter can convert an object of the given type to
/// a , using the specified context.
///
/// An
/// that provides a format context.
/// A that represents the type
/// you want to convert from.
///
/// if this converter can perform the conversion;
/// otherwise, .
///
public override bool CanConvertFrom(
ITypeDescriptorContext context,
Type sourceType)
{
return sourceType == typeof(string) ||
base.CanConvertFrom(context, sourceType);
}
///
/// Converts the given object to the corresponding ,
/// using the specified context and culture information.
///
/// The to
/// use as the current culture.
/// An
/// that provides a
/// format context.
/// The to convert.
///
/// An that represents the converted value.
///
/// The conversion cannot be
/// performed.
public override object ConvertFrom(
ITypeDescriptorContext context,
CultureInfo culture,
object value)
{
if (value == null)
return null;
if (!(value is string))
return base.ConvertFrom(context, culture, value);
string str = (string)value;
if (str.Length == 0 || str == NoType)
return null;
// Try VisualStudio own service first.
//
ITypeResolutionService typeResolver =
(ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));
if (typeResolver != null)
{
Type type = typeResolver.GetType(str);
if (type != null)
return type;
}
return Type.GetType(str);
}
///
/// Returns whether this converter can convert the object to the specified type,
/// using the specified context.
///
/// An
/// that provides
/// a format context.
/// A that represents
/// the type you want to convert to.
///
/// if this converter can perform the conversion;
/// otherwise, .
///
public override bool CanConvertTo(
ITypeDescriptorContext context,
Type destinationType)
{
return destinationType == typeof(string) ||
base.CanConvertTo(context, destinationType);
}
///
/// Converts the given value object to the specified type, using the specified
/// context and culture information.
///
/// A .
/// If null is passed, the current culture is assumed.
/// An
/// that provides
/// a format context.
/// The to convert
/// the value parameter to.
/// The to convert.
///
/// An that represents the converted value.
///
/// The conversion cannot be
/// performed.
///
/// The parameter is null.
public override object ConvertTo(
ITypeDescriptorContext context,
CultureInfo culture,
object value,
Type destinationType)
{
if (destinationType != typeof(string))
return base.ConvertTo(context, culture, value, destinationType);
if (value == null || value.ToString().Length == 0)
return NoType;
return value.ToString();
}
}
}