views:

947

answers:

2

There's a wide variety of colors available when setting colors in XAML in Silverlight, but the options seem limited when dealing with setting colors programmatically.

For example, in Silverlight XAML I can set a Background to "Alice Blue", "Antique White", etc.

But if I try to set that same background in the code-behind, I'm limited to a fairly finite set of colors based on the Colors class... Black, Blue, Brown...White, Yellow. These come into play with something like:

uxPanel.Background = new SolidColorBrush (Colors.Green);

I know I can set any color I'd like via RGB values, as in (where colorsString is something like "112345"):

var brush = new SolidColorBrush ();
var c = new Color
            {
             A = 0xFF,
             R = Convert.ToByte (colorString.Substring (0, 2), 16),
             G = Convert.ToByte (colorString.Substring (2, 2), 16),
             B = Convert.ToByte (colorString.Substring (4, 2), 16)
            };

brush.Color = c;

return (brush);

But how can I tap into the wider variety of color names accessible in XAML or via a style, but set programmatically in my code-behind? Or is this not possible in Silverlight?

+1  A: 

I'm not sure I understand the question. In my code-behind in XAML I can access colours such as "Antique White" via the Colors object:

var c = Colors.AntiqueWhite;

It's not a different set of colours from the ones you can access in XAML.

Colours such as AntiqueWhite are available whether I reference System.Drawing.Color or System.Windows.Media.Colors.

Edit

So it looks like you're talking specifically about the System.Windows.Media.Colors class in Silverlight, which does indeed give you only a limited set of colours to work with. How odd!

I guess the easiest thing to do is define your own class with the ARGB values from the MSDN documentation on the WPF version. Something like:

public static class ExtraColors
{
    private static Color _antiqueWhite = Color.FromArgb(0xFF, 0xFA, 0xEB, 0xD7);
    // etc

    public static Color AntiqueWhite { get { return _antiqueWhite; } }
    // etc
}

Awkward, I know, but it'll at least get you a readable code-accessible list of those extra colours.

Matt Hamilton
His question is referring on Silverlight I guess. In Silverlight Colors enumeration is limited at code behind
Jobi Joy
Oh wow - you're right. http://msdn.microsoft.com/en-us/library/system.windows.media.colors_members(VS.95).aspx
Matt Hamilton
Oh, sorry. I didn't realize there was a diff in the accessible colors between WPF and Silverlight. I'll re-tag the question.
scottmarlowe
Yeah, that is awkward... and ugly. But it looks like the only way.
scottmarlowe
+1  A: 

Someone at silverlight.net posted code to recreate the XAML colors in C#.

Ben M
Thanks for the link. You just saved me a whole lot of time.
scottmarlowe