Programmatically set TextBlock Foreground Color

125,276

Solution 1

 textBlock.Foreground = new SolidColorBrush(Colors.White);

Solution 2

Foreground needs a Brush, so you can use

textBlock.Foreground = Brushes.Navy;

If you want to use the color from RGB or ARGB then

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35)); 

or

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy); 

To get the Color from Hex

textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991")); 

Solution 3

You could use Brushes.White to set the foreground.

myTextBlock.Foreground = Brushes.White;

The Brushes class is located in System.Windows.Media namespace.

Or, you can press Ctrl+. while the cursor is on the unknown class name to automatically add using directive.

Solution 4

To get the Color from Hex.

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

and then set the foreground

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(color); 
Share:
125,276
Admin
Author by

Admin

Updated on July 05, 2022

Comments

  • Admin
    Admin almost 2 years

    Is there a way to do this in Windows Phone 7?

    I can reference the TextBlock in my C# Code, but I don't know exactly how to then set the foreground color of it.

    myTextBlock.Foreground = 
    //not a clue...
    

    Thanks

  • Admin
    Admin over 11 years
    Indian Programmer - Thank you! Tell me, what namespace should one use to use the Brushes class?
  • Admin
    Admin over 11 years
    Thanks! What namespace should one use to get access to the Brushes class? Can't seem to find it..
  • Bibaswann Bandyopadhyay
    Bibaswann Bandyopadhyay almost 10 years
    In the last example also you need System.Windows.Media.Colors.Navy in parenthesis, like TextBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Co‌​lors.Red); , that is of course if you have not referenced the namespace in the beginning of the file
  • Vahid
    Vahid over 9 years
    Is there any "FromHex()" available?
  • barrypicker
    barrypicker over 5 years
    Trying to use the HEX example. Getting Error CS0120 An object reference is required for the non-static field, method, or property 'TypeConverter.ConvertFromString(string)'
  • Chef Pharaoh
    Chef Pharaoh about 5 years
    Great, thanks for also showing how to use hex values too!!
  • Jeff
    Jeff over 4 years
    A variation of this can also be used to check the color which is useful. +1: if ((Color)ColorConverter.ConvertFromString(wpfComponent.Foregr‌​ound.ToString()) == Colors.Red) { ...