Multiple Colors In TextBlock
Asked Answered
Z

4

11

Is it possible to add dynamic colors to a TextBlock ..i.e. have one character in one color and the next in another color.

<TextBlock Text="{Binding no}" TextWrapping="Wrap" Margin="10,0,0,0" Style="{StaticResource PhoneTextSubtleStyle}" FontSize="40" Foreground="#A400C4FF" >
  // Can we add something here to specify what colours for what chars
</TextBlock>

Basically I input a dynamic 4 character sequence from no. I've bound it to this TextBlock inside a ListBox. Is it possible to have the characters in different colors.

If so is it possible to add these colors dynamically for eg. If I click a button certain characters change color?

Thank You. Any Help is appreciated.

Zolazoldi answered 3/12, 2011 at 4:38 Comment(0)
N
37

Actually, you can, which can come in handy when you're doing a StringFormat on a data bound Textblock or a number of other places.

If you did want to try it though, like here's an SL example for a form label that puts a red asterisk next to the text Required Fields, but then can also add more stuff to it as shown in the example. Should work for Silverlight, WPF, UWP, etc...

<TextBlock>
      <Run Text="*" Foreground="#FFE10101"/><Run Text="Required Line" />
      <Run Text="Red" Foreground="Red"/>
      <Run Text="Blue" Foreground="Blue"/>
      <Run Text="{Binding SomeString, StringFormat='Hell ya you can make \{0\} a different color!'}" Foreground="Orange"/>
</TextBlock>
Navarrete answered 7/8, 2012 at 19:27 Comment(0)
P
0

I'm developing for Mango with the WP7 SDK. You can use a <Run>. It seems a little buggy on WP7 , you have to add a spaces on the Run.Text property to get the spacing correct:

<TextBlock>Hello<Run Foreground="Bisque" Text=" Holla "></Run>and hello again!</TextBlock>;
Petronilapetronilla answered 10/2, 2012 at 0:53 Comment(1)
How can I set the text in this Run tag dynamically ?Bazluke
W
0

to set foreground color dynamically to a textblock

use: txtblockname.Foreground= new SolidColorBrush(Colors.Yellow);

Watt answered 6/12, 2018 at 9:16 Comment(0)
B
-3

The TextBlock does not support multiple Foreground colors.

You could recreate this behaviour by using multiple textblocks (one for each letter) and placing them within a wrappanel. You could then change the color of individual characters/letters as you wish.
Beware of the probable performance impact this may have. The margins around individual letters will need to be adjusted to recreate standard behaviour though. Be especially careful around punctuation.

Babbage answered 5/12, 2011 at 11:15 Comment(1)
So, two things. 1. Yes it does with <Run> in XAML, or 2. with c# create a new instance of a run and use the .add method of textblock.Inlines to add this instance. I understand your comment was from 2011 but maybe edit it or remove so it isn't misleading 10 years later.Gangue

© 2022 - 2024 — McMap. All rights reserved.