Can I have multiple colors in a single TextBlock in WPF?
Asked Answered
S

4

10

I have a line of text in a textblock that reads:

"Detected [gesture] with an accuracy of [accuracy]"

In WPF, is it possible for me to be able to change the color of the elements within a textblock? Can I have a textblock be multiple colors? For example, I would like the whole TextBlock to be black except the gesture name, which I would like to be red.

Is this possible in WPF?

Searching answered 24/4, 2010 at 17:28 Comment(0)
H
15

See if this helps:

 <TextBlock>
      Detected
      <TextBlock Text="{Binding Gesture}" Foreground="Red" />
      with an accuracy of
      <TextBlock Text="{Binding Accuracy}" />
 </TextBlock>
Hamlet answered 24/4, 2010 at 17:57 Comment(1)
Only issue is that these 4 areas of text (Detected, Gesture, with an accuracy of, and Accuracy) will not be on the same line - they'll be single-spaced on different lines, instead. But I like the concept.Wallsend
S
2

I think what you mean is like this( not styling for textblock):

<TextBlock  FontSize="25" >
   <Run Text="Detected [" Foreground="Red"/><Run Text="gesture" Foreground="Gray"/>
   <Run Text="] with an accuracy of [" Foreground="Yellow"/><Run Text="accuracy]" Foreground="Green"/>
</TextBlock>

Note: every enter(or new line) between Run tag make have space between them.

Spermaceti answered 1/7, 2020 at 23:34 Comment(0)
A
1

I know this post is old, but have you tried this?? You can actually add multi colored text, this way in a TextBlock..

Xaml: <TextBlock x:Name="txt_Txt"/>


foreach (var itm5 in "! Hello World !; %Hello World%".Split(';'))
{
       if (txt_Txt.Inlines.Count() > 0)
           txt_Txt.Inlines.Add(new Run("\r\n"));
       foreach (var letter in itm5)
       {
            if (char.IsSymbol(letter))
               txt_Txt.Inlines.Add(new Run(letter.ToString()) { Foreground = Brushes.Red });
            else
                txt_Txt.Inlines.Add(new Run(letter.ToString()) { Foreground = Brushes.Black });
        }
}
Apologize answered 24/10, 2018 at 16:58 Comment(0)
F
0

you can use a RichTextBox for that and set IsReadOnly = true

Franko answered 24/4, 2010 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.