views:

1579

answers:

5

I am trying to set a colour of an elipse object in code behind. So far I'm doing it by using the SolidColorBrush method. Wonder if there is a way to insert the colour value in hexadecimal, like in css.

Here is a code that I am using:

ellipse.Fill = new SolidColorBrush(Colors.Yellow);
+2  A: 

Something like this would work

ellipse.Fill = 
    new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF00DD"));

(Edit: It looks like this is WPF only. Alex Golesh has a blog post here about his Silverlight ColorConverter)

Although I prefer the Color.FromRgb method

byte r = 255;
byte g = 0;
byte b = 221;
ellipse.Fill = new SolidColorBrush(Color.FromRgb(r,g,b));
Ray
What do I need to inherit to use the ColorConverter?
Drahcir
In WPF it's in System.Windows.Media, in Silverlight, well it's not. See my edit.
Ray
+1  A: 

I wrote a simple color converter function to solve this problem. The happy faces are really the number 8 and a parentheses, like this: 8).

+1  A: 

From MSDN

SolidColorBrush mySolidColorBrush = new SolidColorBrush();

// Describes the brush's color using RGB values. 
// Each value has a range of 0-255.
mySolidColorBrush.Color = Color.FromArgb(255, 0, 0, 255);
myRgbRectangle.Fill = mySolidColorBrush;
PaulB
A: 

Of course, you could also do something like this (using the hex numbers in the FromArgb function):

SolidColorBrush mySolidColorBrush = new SolidColorBrush();

// Describes the brush's color using RGB HEX values. 
// Each value has a range of 0-255. Use 0x for HEX numbers
mySolidColorBrush.Color = Color.FromArgb(255, 0xFF, 0xC0, 0xD0);
myRgbRectangle.Fill = mySolidColorBrush;
WPCoder
A: 

Another one small, fast and usefull

public static Color ToColor(this uint argb)
{
    return Color.FromArgb((byte)((argb & -16777216) >> 0x18),
                          (byte)((argb & 0xff0000) >> 0x10),
                          (byte)((argb & 0xff00) >> 8),
                          (byte)(argb & 0xff));
}

Use in code

SolidColorBrush scb  = new SolidColorBrush (0xFFABCDEF.ToColor());

of course it is need to use 0xFFFFFFFF (uint) notation insted "#FFFFFFFF" (string) but, I shure it's no big deal.

FFire