Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I dynamically make part of the TextBlock.Text to different colour?

Tags:

c#

wpf

I have TextBlock in my main form. I set the Text property to different strings during the application run.

I would like to be able to colour parts of particular strings.

Pseudo code:

if(a < 0) txbStatus.Text = string.Format("{0} <RED>{1}</RED>",  a, b);
     else txbStatus.Text = string.Format("{0} <BLUE>{1}</RED>", a, b);
like image 452
Boppity Bop Avatar asked Nov 30 '22 05:11

Boppity Bop


2 Answers

You can split your string the way u want and then using a foreach() loop for that split string try

TextBlockName.Inlines.Add(new Run("colored text") {Foreground = Brushes.Blue});
like image 182
Johnny Avatar answered Dec 05 '22 06:12

Johnny


The content of a TextBox doesn't have to be just a string, but a collection of Inlines:

txbStatus.Inlines.Clear();
txbStatus.Inlines.Add(new Run("normal color, "));
txbStatus.Inlines.Add(new Run("colored text") { Foreground = Brushes.Red });
like image 42
svick Avatar answered Dec 05 '22 06:12

svick