WebColorConverter.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Namespace: System.Web.UI.WebControls
  3. * Class: WebColorConverter
  4. *
  5. * Author: Gaurav Vaish, Gonzalo Paniagua Javier
  6. * Maintainer: [email protected]
  7. * Contact: <[email protected]>, <[email protected]>, <[email protected]>
  8. * Implementation: yes
  9. * Status: 100%
  10. *
  11. * (C) Gaurav Vaish (2002)
  12. * (c) 2002 Ximian, Inc. (http://www.ximian.com)
  13. */
  14. using System;
  15. using System.Globalization;
  16. using System.ComponentModel;
  17. using System.Drawing;
  18. using System.Web;
  19. using System.Web.UI;
  20. namespace System.Web.UI.WebControls
  21. {
  22. public class WebColorConverter : ColorConverter
  23. {
  24. public override object ConvertFrom (ITypeDescriptorContext context,
  25. CultureInfo culture,
  26. object value)
  27. {
  28. if (value is string) {
  29. string val = ((string) value).Trim ();
  30. if(val == String.Empty || val.Length == 0)
  31. return Color.Empty;
  32. NumberStyles style = (val [0] == '#') ? NumberStyles.HexNumber :
  33. NumberStyles.None;
  34. try {
  35. int n = Int32.Parse (val.Substring (1), style);
  36. return Color.FromArgb (n);
  37. } catch {
  38. Color c = Color.FromName (val);
  39. if (c.A != 0 || c.R != 0 || c.B != 0 || c.G != 0)
  40. return c;
  41. }
  42. }
  43. return base.ConvertFrom(context, culture, value);
  44. }
  45. public override object ConvertTo (ITypeDescriptorContext context,
  46. CultureInfo culture,
  47. object value,
  48. Type destinationType)
  49. {
  50. if (destinationType == null)
  51. throw new ArgumentNullException ("destinationType");
  52. if (destinationType == typeof (String) && value != null) {
  53. Color c = (Color) value;
  54. if (c == Color.Empty)
  55. return String.Empty;
  56. if (c.IsNamedColor || c.IsSystemColor)
  57. return c.Name;
  58. return String.Format ("#{0:X2}{1:X2}{2:X2}{3:X2}", c.A, c.R, c.G, c.B);
  59. }
  60. return base.ConvertTo(context, culture, value, destinationType);
  61. }
  62. }
  63. }