ColorConverter in Silverlight 2

April 29, 2008

Do you miss ColorConverter class in Silverlight? I do… Really…


I today bind Background property to some color value received from JavaScript. JavaScript provides a value in string format, something like “#FFDEDEDE”. The way to bind to background property is to prepare SolidColorBrush, and the way to SolidColrBrush lies via Color. And how one can make Color object from string? In full .NET framework there is a handy class, called ColorConverter which provides such functionality… In Silverlight System.Drawing doesn’t exists, and so ColorConverter… And so my plan to convert string to System.Windows.Media.Color was ruined…


To solve this I created class, called ColorConveter which implements IValueConverter  interface and could be used as converter for binding purposes…



   1: public class ColorConverter : IValueConverter
   2: {
   3:  
   4:     #region IValueConverter Members
   5:  
   6:     //[ValueConversion(typeof(SolidColorBrush), typeof(string))]
   7:     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
   8:     {
   9:         string val = value.ToString();
  10:         val = val.Replace(“#”, “”);
  11:  
  12:         byte a = System.Convert.ToByte(“ff”, 16);
  13:         byte pos = 0;
  14:         if (val.Length == 8)
  15:         {
  16:             a = System.Convert.ToByte(val.Substring(pos, 2), 16);
  17:             pos = 2;
  18:         }
  19:  
  20:         byte r = System.Convert.ToByte(val.Substring(pos, 2), 16);
  21:         pos += 2;
  22:  
  23:         byte g = System.Convert.ToByte(val.Substring(pos, 2), 16);
  24:         pos += 2;
  25:  
  26:         byte b = System.Convert.ToByte(val.Substring(pos, 2), 16);
  27:  
  28:         Color col = Color.FromArgb(a, r, g, b);
  29:  
  30:         return new SolidColorBrush(col);
  31:     }
  32:  
  33:     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  34:     {
  35:         SolidColorBrush val = value as SolidColorBrush;
  36:         return “#” + val.Color.A.ToString() + val.Color.R.ToString() + val.Color.G.ToString() + val.Color.B.ToString();
  37:     }
  38:  
  39:     #endregion
  40: }

Sample XAML:



   1: <UserControl x:Class=”ColorConverter.Page”
   2:     xmlns=”http://schemas.microsoft.com/client/2007″ 
   3:     xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” 
   4:     xmlns:local=”clr-namespace:ColorConverter”
   5:     Width=”400″ Height=”300″>
   6:     
   7:     <UserControl.Resources>
   8:         <local:ColorConverter x:Key=”colorConverter”/>
   9:     </UserControl.Resources>
  10:     
  11:     <Grid x:Name=”LayoutRoot” Background=”White”>
  12:         <Border Background=”{Binding TextColor, Mode=OneWay, Converter={StaticResource colorConverter}}”>
  13:             <TextBlock Text=”Colored Test” Foreground=”Blue”/>
  14:         </Border>
  15:     </Grid>
  16: </UserControl>

Sample code for XAML file:



   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Windows;
   5: using System.Windows.Controls;
   6: using System.Windows.Documents;
   7: using System.Windows.Input;
   8: using System.Windows.Media;
   9: using System.Windows.Media.Animation;
  10: using System.Windows.Shapes;
  11:  
  12: namespace ColorConverter
  13: {
  14:     public partial class Page : UserControl
  15:     {
  16:         public Page()
  17:         {
  18:             InitializeComponent();
  19:  
  20:             TextColor = “#FF00FF13”;
  21:             this.DataContext = this;
  22:         }
  23:  
  24:         public string TextColor
  25:         {
  26:             get { return (string)GetValue(TextColorProperty); }
  27:             set { SetValue(TextColorProperty, value); }
  28:         }
  29:  
  30:         // Using a DependencyProperty as the backing store for TextColor.  This enables animation, styling, binding, etc…
  31:         public static readonly DependencyProperty TextColorProperty =
  32:             DependencyProperty.Register(“TextColor”, typeof(string), typeof(Page), null);
  33:  
  34:     }
  35: }

Updated sample code for RTW version:



   1: public partial class Page : UserControl
   2: {
   3:     ColorDetails textColor = new ColorDetails();
   4:  
   5:     public Page()
   6:     {
   7:         InitializeComponent();
   8:  
   9:         textColor.TextColor = “#FF00FF13”;
  10:  
  11:         this.DataContext = textColor;
  12:     }
  13: }
  14:  
  15: public class ColorDetails : INotifyPropertyChanged
  16: {
  17:   string str = “”;
  18:  
  19:   public string TextColor
  20:   {
  21:     get { return str; }
  22:     set
  23:     {
  24:       str = value;
  25:  
  26:       if (null != PropertyChanged)
  27:         PropertyChanged(this, new PropertyChangedEventArgs(“TextColor”));
  28:     }
  29:   }
  30:  
  31:   public event PropertyChangedEventHandler PropertyChanged;
  32: }

Source solution here.


Enjoy,


Alex

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

7 comments

  1. N. RamseySeptember 19, 2008 ื‘ 15:51

    This is awesome. Thanks a lot Alex!

    Reply
  2. JordanOctober 8, 2008 ื‘ 17:14

    Thanks mate, you just saved me some code ๐Ÿ™‚ ๐Ÿ™‚

    Reply
  3. DanielDecember 12, 2008 ื‘ 4:03

    Hi! Is there a version that works with the release version of Silverlight 2? The automatic convertion of Visual Studio 2008 recieves errors.

    Reply
  4. Alex GoleshDecember 13, 2008 ื‘ 1:08

    Daniel,

    The converter itself works fine. The binding in tester app should be changed a little to RTW style (this post was written at Beta 1 timeframe).
    See updated Sample code in post.

    Alex

    Reply
  5. Mark VrankovichSeptember 9, 2009 ื‘ 3:06

    Hi, this is how I solved this problem:

    Where the input variable colour is a string hex value like “#e42217”

    int x = Convert.ToInt32(colour.Replace(“#”, “0x”), 16);
    byte red = (byte)((x & 0xff0000) >> 16);
    byte green = (byte)((x & 0xff00) >> 8);
    byte blue = (byte)(x & 0xff);

    I hope that helps someone oneday ๐Ÿ™‚

    Reply
  6. Alex PereverzyevOctober 13, 2011 ื‘ 23:46

    Thanks a lot for the code snippet!

    Reply
  7. DannyApril 12, 2012 ื‘ 3:10

    good work. You saved me some coding.

    Reply