2

I am trying to make each line of text on a WPF textblock display in a different color. I have the following code which makes the entire block's font color purple because that's the last color it's set to. How can I make it so each potion is displayed in a different color?

    private void btnShowPotions_Click(object sender, RoutedEventArgs e) {

        tbPotionInfo.Foreground = Brushes.Green;
        tbPotionInfo.Text = smallPotion.Name + "(" + smallPotion.AffectValue + ")\r\n";
        tbPotionInfo.Foreground = Brushes.Blue;
        tbPotionInfo.Text += mediumPotion.Name + "(" + mediumPotion.AffectValue + ")\r\n";
        tbPotionInfo.Foreground = Brushes.Red;
        tbPotionInfo.Text += largePotion.Name + "(" + largePotion.AffectValue + ")\r\n";
        tbPotionInfo.Foreground = Brushes.Purple;
        tbPotionInfo.Text += extremePotion.Name + "(" + extremePotion.AffectValue + ")\r\n";
    }
9
  • 1
    you can make use of Run here Commented Mar 4, 2016 at 6:59
  • Take a look at this wpf-tutorial.com/basic-controls/… - specifically the section named RUN and SPAN. Commented Mar 4, 2016 at 6:59
  • use richtextbox and set it to readonly , or you have to setup textblock with one textbox for each color Commented Mar 4, 2016 at 7:00
  • @Thorarins you're wrong - with the usage of Runs or Spans he will be working with one TextBlock only. Besides - RichTextBox is reaaaaally slow and laggy. Have you actually tried to use it in your apps? Commented Mar 4, 2016 at 7:02
  • 1
    @Gopichandar is already ahead of me ;) Commented Mar 4, 2016 at 7:07

2 Answers 2

9

You can make use of Run.

Here is the sample of how to use the Run

Run run = new Run(smallPotion.Name + "(" + smallPotion.AffectValue + ")\r\n");
run.Foreground = Brushes.Green;
tbPotionInfo.Inlines.Add(run);   

run = new Run(mediumPotion.Name + "(" + mediumPotion.AffectValue + ")\r\n");
run.Foreground = Brushes.Blue;
tbPotionInfo.Inlines.Add(run);        
...

Haven't verified but I hope it will help you.

Sign up to request clarification or add additional context in comments.

Comments

4

Use textblock like this

<TextBlock>
      <TextBlock Name="tbSmallPotion" Foreground="Green"/
      <TextBlock Text="tbMediumPotion"Foreground="Blue"/>
 </TextBlock>

and set the values

tbSmallPotion.Text = smallPotion.Name + "(" + smallPotion.AffectValue + ")\r\n";
tbMediumPotion.Text = mediumPotion.Name + "(" + mediumPotion.AffectValue + ")\r\n";

1 Comment

Yes this would work, I ended up going with Gopichandar's solution for the simplicity of having one textblock.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.