Geeks With Blogs
Darren Fieldhouse

I’m working on a project that runs on a smart phone using the compact framework. The user needs to be able to enter the name of a colour (e.g. “Green”) and the app needs to be able to display an icon in that colour.

My first thought was to use the FromKnownColor() static method on the Color class, but it turns out that’s not implemented in the compact framework. Given that the colour class has static properties for all the well known colours, all with the correct names, I felt there must be some way to make use of that to translate my user inputted string into a color object (e.g. translate “Green” to Color.Green).

Using reflection I can get a list of static properties like this:

GetType(Color).GetProperties(Reflection.BindingFlags.Static Or Reflection.BindingFlags.Public)

Using the Where() extension method, I filter the list of PropertyInfo objects down to the one I’m interested in:

.Where(Function(p) p.Name = colourName).SingleOrDefault()

The SingleOrDefault() method is used to remove the single PropertyInfo object from the result list (or return nothing if there was no match). The last set is to call the GetValue() method to get the value of the property (i.e. the Color object). This would normally take a Color object as a parameter, but as it is a static property we pass Nothing (null) in instead. Here is the final function that takes a colour name as a parameter and returns a Color object:

Public Function FromKnownColor(ByVal colorName As String) As Color
  Dim _PropertyInfo = GetType(Color).GetProperties(Reflection.BindingFlags.Static Or Reflection.BindingFlags.Public).Where(Function(p) p.Name = colorName).SingleOrDefault()

 

  If _PropertyInfo IsNot Nothing Then
    Return _PropertyInfo.GetValue(Nothing, Nothing)
  Else
    Return Nothing
  End If
End Function

kick it on DotNetKicks.com

Posted on Wednesday, January 14, 2009 12:32 PM | Back to top


Comments on this post: Using LINQ and Reflection to implement FromKnownColor in the compact framework

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © DarrenFieldhouse | Powered by: GeeksWithBlogs.net | Join free