How to change the Foreground color from code behind


In this article, I will explain how to change the color i.e Foreground color of TextBlock in the code behind file or at run time.

Creating a TextBlock



First of all, create a TextBlock in the XAML page and give it a name so that we can access it in the code behind file at run-time.
I have created a TextBlock named "lblStatus" and assigned some property. The Foreground color is set to "Green"
Also add a Button.So, that when you click the button we will change the Foreground color of the Text in the TextBlock
I have created a Button name "btnChangeColor" and assigned some properties and and "Click" event handler "btnChangeColor_Click"


1.) TextBlock x:Name="lblStatus" Width="100" Height="30" Text="Hi This is Demo"
2.) Button x:Name="btnChangeColor" Content="Change Color" Click="btnChangeColor_Click"


Changing the Foreground in Code Behind



Now go to the event handler "btnChangeColor_Click" and add the following line (if you want to change the color to basic colors).


myTextBlock.Foreground = new SolidColorBrush(Colors.Red);


if you want to change the color and you know the "RGB" values then use this line


myTextBlock.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));


Note: I have removed the "<" and "/>" sign before and after the "TextBlock" and "Button". If I keep then then the browser(Silverlight plug-in) interprets the XAML code and shows a "TextBlock" and "Button" instead of the code.


Comments

Guest Author: username28 Jan 2012

Thank you. I was looking exactly for this information.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: