locked
Rich Text in teXt block through code. RRS feed

  • Question

  • The string "The rainbow" needs to have different colors for each word. As far as I'm concerned (my concerns aren't of any great extension) TextBlocks can only have one color. So guess what I tried to do? I wrote me some code that basically parses the string I need to be printed sample string to parse: I am SO COLORFUL compared to you rusty lookin' jokers What I got was "I am so Colorful" Sitting under "compared to you" which is all under "you rusty lookin' jokers" Basically I tried creating multiple textblock objects that were added to a grid object... but it failed (-_-) What does the team think i should do? I can't write it in XAML because the program has to read content from a file. ( i don't even know how to write rich text in xaml )
    Thursday, June 10, 2010 3:37 PM

Answers

  • string [] parts = "I am so Colorful".Split(new char [] {' '});
    foreach(string part in parts)
    {
         Span span = new Span();
         Run run = new Run { Text=part, Foreground = new SolidColorBrush(Colors.Red) };
         span.Inlines.Add(run);
         MyRichTextBox.Blocks[0].Inlines.Add(span); //Blocks[0] is a paragraph
    }

    Thursday, June 10, 2010 4:09 PM

All replies