Changing the Font Colour (Foreground) of textblock on Button Press Event RRS feed

  • Question

  • Hi

    I have a quick question. I want the Foreground colour to be changed when the user clicks on a specific button. I know how to change the Width, Text et al by using the TextBlock.Text = or TextBlock.Width = commands. But I just can't seem to figure out how to change the specific TextBlocks Foreground colour to this colour #FF00AEFF

    Any help would be appreciated.

    Tuesday, June 17, 2014 2:07 PM


All replies

  • You can set the Foreground property to a pre-defined Brush:
    textBlock.Foreground = Brushes.Green;

    ...or to your own Brush object:

       string hexCode = "#FF00AEFF";
       System.Windows.Media.Color color = new System.Windows.Media.Color();
       color.A = byte.Parse(hexCode.Substring(1, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
       color.R = byte.Parse(hexCode.Substring(3, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
       color.G = byte.Parse(hexCode.Substring(5, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
       color.B = byte.Parse(hexCode.Substring(7, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
       SolidColorBrush brush = new SolidColorBrush(color);
       textBlock.Foreground = brush;

    Tuesday, June 17, 2014 2:18 PM
  • Hi

    None of that code works in Windows RT (Windows 8 Store Apps).

    Tuesday, June 17, 2014 2:32 PM
  • Try this for pre-defined brushes:
    textBlock.Foreground = new SolidColorBrush(Windows.UI.Colors.Green);

    ...or you could use the Color.FromArgb method to create a Color object from numeric values:

    textBlock.Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0, 0xAE, 0xFF));

    • Marked as answer by DreyerSmit Tuesday, June 17, 2014 2:44 PM
    Tuesday, June 17, 2014 2:42 PM
  • That works perfectly. Thanks :)
    Tuesday, June 17, 2014 2:44 PM
  • Generally the best way is to set your colour in a resource. This allows using full colour in default modes with automatic fall back to a high contrast colour in high contrast modes. Depending on the scenario you may want to apply a style rather than a colour so you can include bold or italic in the highlight.

    The code will be something like (appropriate as I'm not on a dev machine)

    MyTextBlock.Foreground =Resources["HighlightColour"] as Brush;


    MyTextBlock.Style = Resources["HighlightResource"] as Style;
    And in Xaml
        <!-- Collection of items displayed by this page --> 
        < ResourceDictionary> 
                < ResourceDictionary x:Key="Default"> 
                    < SolidColorBrush  x:Key="HighlightColour" Color="Green"/> 
                < ResourceDictionary x:Key="HighContrast"> 
                    < SolidColorBrush x:Key="HighlightColour" Color="{ThemeResource SystemColorWindowColor}" /> 

    Tuesday, June 17, 2014 2:49 PM