65

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

good-to-know
  • 680
  • 2
  • 15
  • 30

4 Answers4

141
 textBlock.Foreground = new SolidColorBrush(Colors.White);
Rahul Singh
  • 20,580
  • 5
  • 32
  • 49
Diana Mikhasyova
  • 1,520
  • 1
  • 9
  • 10
58

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")); 
Raz Luvaton
  • 816
  • 1
  • 12
  • 22
Kishore Kumar
  • 11,843
  • 26
  • 86
  • 149
  • Indian Programmer - Thank you! Tell me, what namespace should one use to use the Brushes class? –  Oct 04 '12 at 12:51
  • 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.Colors.Red); , that is of course if you have not referenced the namespace in the beginning of the file – Bibaswann Bandyopadhyay Jul 31 '14 at 12:55
  • Is there any "FromHex()" available? – Vahid Dec 24 '14 at 09:09
  • 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)' – barrypicker Aug 22 '18 at 15:53
  • Great, thanks for also showing how to use hex values too!! – Chef Pharaoh Apr 16 '19 at 21:55
12

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.

AgentFire
  • 8,224
  • 6
  • 39
  • 84
  • 1
    Thanks! What namespace should one use to get access to the Brushes class? Can't seem to find it.. –  Oct 04 '12 at 12:52
10

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); 
Kishore Kumar
  • 11,843
  • 26
  • 86
  • 149
  • A variation of this can also be used to check the color which is useful. +1: if ((Color)ColorConverter.ConvertFromString(wpfComponent.Foreground.ToString()) == Colors.Red) { ... – Jeff Dec 31 '19 at 16:10