In Depth Banner
Skip Navigation Links

Select your preferred language

Transparency type converter.

using System;

using System.ComponentModel;

 

namespace TypeEditorsCS

{

  /// <summary>

  /// Summary description for TransparencyConverter.

  /// </summary>

  public class TransparencyConverter : TypeConverter

  {

    public TransparencyConverter()

    {

    }

 

    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)

    {

      if(sourceType == typeof(string))

        return true;

      return base.CanConvertFrom (context, sourceType);

    }

 

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)

    {

      if(destinationType == typeof(string))

        return true;

      return base.CanConvertTo (context, destinationType);

    }

 

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)

    {

      if(value is string)

      {

        string s=(string)value;

        int n=s.IndexOf("%");

        if(n>-1)

          s=s.Substring(0,n);

        try

        {

          int i=int.Parse(s);

          i=i>100 ? 100 : i<0 ? 0 : i;

          return 255-(i*255/100);

        }

        catch(Exception)

        {

          return 0;

        }

      }

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

    }

 

    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)

    {

      if(destinationType==typeof(string))

      {

        return string.Format("{0}%",((255-(int)value)*100/255).ToString(""));

      }

      return base.ConvertTo (context, culture, value, destinationType);

    }

  }

}

 

Return to the article.

 

 

Copyright © Bob Powell 2003-2009. All rights reserved