Click here to Skip to main content
15,117,095 members
Articles / Silverlight
Posted 5 Aug 2010

Tagged as


4 bookmarked

Silverlight: Use KnownColor Through the Backdoor

Rate me:
Please Sign up or sign in to vote.
5.00/5 (10 votes)
12 Aug 2010CPOL2 min read
Get around another irrational and arbitrary omission in Silverlight
Look at the 3rd edit for my final solution (I left the existing stuff here so you could see the different ways to approach the problem).


I have been puzzling over an annoyance in Silverlight involving the use of known color values. In XAML, you can set a color property with one of dozens of colors - by name. However, that same list of colors isn't available (that I could find) from the code-behind (I hate the word "code-behind") unless you coded it up yourself.

I eventually came up with an idea about how to do it, and it might be ugly, but it's certainly less hassle than writing your own KnownColor enumeration. Using the XamlLoader, simply create a xaml string that creates a UIElement, set one of the element's color properties to the specified color, and then read the appropriate property. I know, if you specify a color that doesn't exist, an exception will be thrown, but hey, some forethought in the code will get around that issue. Here's the method:

private Color GetColorByName(string nameOfColor)
    // Set a default color.
    Color color = Colors.Black;

        // I create a formatted string because I like formatted strings 
        // (and it saved some typing). We're going to create a 
        // rectange, set it's fill property to the specified color and 
        // see what happens.
	string xaml = string.Format("<Rectangle xmlns=\"{0}/presentation\" xmlns:x=\"{0}\" Fill=\"{1}\" />", 
	"", nameOfColor);

        // Load the xaml - this line will throw an exception if an 
        // invalid color is specified, but that's okay - we're just 
        // going to eat the exception.  Note: the color doesn't have to 
        // be capitalized, but it DOES have to be spelled correctly.
        Rectangle rect = (Rectangle)XamlReader.Load(xaml);
        color = (Color)rect.Fill.GetValue(SolidColorBrush.ColorProperty);
        // Yummy!

    // Return the resulting color (it will be the default color if an 
    // exception was thrown.
    return color;

The method above will return Colors.Black if you specified the color "blah", or Colors.Red if you specified "Red" (or "red").

EDIT #1 - I realize that using XamlReader is inefficient, but it's convenient, and as someone else already mentioned, you could easily build a cache of colors already "found" so you don't have to hammer the system with XamlReader. This technique is merely one approach to actually getting the values.

EDIT #2 - You could (and actually should) also use reflection, like so:

// put this code in the try block above
Type colorType = (typeof(System.Windows.Media.Colors));
if (colorType.GetProperty(rgbColor) != null)
    object obj = colorType.InvokeMember(rgbColor, BindingFlags.GetProperty, null, null, null);
    if (obj != null)
        color = (Color)obj;

Using reflection is 500 times faster (no kidding) than using XamlReader. I tried 100,000 iterations using both, and XamlReader took 5.6 seconds to finish, while using reflection took just 0.7 seconds. I'd say that using reflection is the better approach with one really big exception - the method above only returns one of the colors we can already get to. In other words, it's pointless.

Edit #3 -------------------

I really wasn't happy with my solution, so I bit the bullet, and did the following. First, I defined an enumerator with the appropriate names/values. I want apologize ahead of time for the formatting of this code block, but listing each color on its own line would have made the tip WAY to long (as if it wasn't already).

public enum KnownColors : uint {
Next, I used some code from a previous tip I posted that allows nme to retrieve an enum value using a string:

public static T StringToEnum<T>(string value, T defaultValue)
	T enumValue = (Enum.IsDefined(typeof(T), value)) ? (T)Enum.Parse(typeof(T), value, true) : defaultValue;
	return enumValue;
And finally, I wrote the method that combines the enum and the enum retrieval method to get an actual color.

// call this method
public static Color FromColorName(string rgbColor)
	uint color = (uint)StringToEnum(rgbColor, KnownColors.Black);
	return Color.FromArgb((byte)(color >> 24),
                              (byte)(color >> 16),
                              (byte)(color >> 8),
While a little "bulkier" in its setup, this really is ultimately the best way to perform the task at hand. You could also create an extension method for the enum that does all the stuff I did in the two separate methods if that blows up your skirt.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

QuestionToo much code & work Pin
sensboston30-Sep-14 17:54
Membersensboston30-Sep-14 17:54 
AnswerRe: Too much code & work Pin
#realJSOP1-Oct-14 8:12
mva#realJSOP1-Oct-14 8:12 
GeneralRe: Too much code & work Pin
sensboston2-Oct-14 6:47
Membersensboston2-Oct-14 6:47 
GeneralRe 3rd edit. I suspect that that would be quicker than the p... Pin
Henry Minute12-Aug-10 5:52
MemberHenry Minute12-Aug-10 5:52 
GeneralReason for my vote of 1 Not a proper way to get the color fr... Pin
Kunal Chowdhury «IN»8-Aug-10 8:25
professionalKunal Chowdhury «IN»8-Aug-10 8:25 
GeneralPost 2nd edit. Nifty! Pin
Henry Minute6-Aug-10 1:22
MemberHenry Minute6-Aug-10 1:22 
GeneralReason for my vote of 5 Thank you for sharing this tip. Pin
linuxjr5-Aug-10 10:13
professionallinuxjr5-Aug-10 10:13 
GeneralYou have a typo in your code. Your method takes "nameOfColor... Pin
Yusuf5-Aug-10 8:28
MemberYusuf5-Aug-10 8:28 
You have a typo in your code. Your method takes "nameOfColor", but in your xaml you refer to "colorName" which does not exist.
GeneralI'm guessing that XamlReader.Load() is bad for performance, ... Pin
Jörgen Sigvardsson5-Aug-10 8:11
MemberJörgen Sigvardsson5-Aug-10 8:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.