Introduction:
Hi Guys,HAPPY DIWALI TO YOU AND TO ALL YOUR FAMILY MEMBERS...!As a long time i wrote my previous article .Now i am back to write my next article ,Ok all right!
In this article i want share a simple tip for "How to programmatically set TextBlock Foreground color with Hex Color(Ex:#5490CC) in WindowsPhone "
Description:
You may think this is very silly article.But i am sure it may helpful for you in future.This is the very real time requirement and some times we may need to set color code /hex color expressions to our UI elements .Have you ever tried to set Hex color to your UI element?,Ok i will explain,in this sample i taken TextBlock control and trying to programatically set Foreground color with Hex color (Ex:#5490CC) in windowsphone
XAML
<TextBlock Name="TxtBlck" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="15,0,0,0" />
Generally we are set foreground color like below,but this is not applicable when we are trying to set color codes(Ex:#5490CC)
C#
TxtBlck.Foreground = new new SolidColorBrush(Colors.Red);//Set color stringsTxtBlck.Foreground = new new SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 226, 111, 15));//Set RGB color
So that to set hex color codes follow below steps.
Step1:
This is method to convert hex color in to color value .
C#
public Color ConvertStringToColor(String hex) { hex = hex.Replace("#", ""); byte a = 255; byte r = 255; byte g = 255; byte b = 255; int start = 0; //handle ARGB strings (8 characters long) if (hex.Length == 8) { a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber); start = 2; } //convert RGB characters to bytes r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber); g = byte.Parse(hex.Substring(start + 2, 2), System.Globalization.NumberStyles.HexNumber); b = byte.Parse(hex.Substring(start + 4, 2), System.Globalization.NumberStyles.HexNumber); return Color.FromArgb(a, r, g, b); }
So that finally we can use above method like this.
C#
TxtBlck.Foreground = new SolidColorBrush(ConvertStringToColor("#5490CC"));
FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.
Follow me always at @Subramanyam_B
Have a nice day by Subramanyam Raju :)
very helpful thanks!!!!!!!!!!!
ReplyDelete