In general, I have been fighting for 2 days with RichTextBox , I can’t master it, I have a console server, it is redirecting to RichTextBox ( WPF ), so I can’t understand how I can make those strings in RichTextBox with content ( Log, Error, Warning ) were painted in the appropriate colors, and everything else remained an arbitrary color, I can not understand how to do this, please kindly sketch an example please. Thank.

enter image description here

  • On c ++, an example is here ru.stackoverflow.com/a/555843/17974 and for c # the names are similar, something like this. - nick_n_a
  • These are the advantages I can't do) - Malcolm
  • I have almost watched everything here already, this is a bit wrong, and too much for such a simple idea - Malcolm

1 answer 1

Well, here's a simple example.

XAML:

<RichTextBox x:Name="RTB" Background="Black" TextBlock.FontWeight="Bold"/> 

Code-behind:

 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); RTB.Document.Blocks.Clear(); Work(); } async void Work() { await Task.Delay(1000); AddWithColor("First", Colors.White); await Task.Delay(1000); AddWithColor("Second", Colors.Green); await Task.Delay(1000); AddWithColor("Third", Colors.Red); await Task.Delay(1000); AddWithColor("Fourth", Colors.Yellow); } void AddWithColor(string s, Color color) { var text = new Run(s) { Foreground = new SolidColorBrush(color) }; var p = new Paragraph(text) { Margin = new Thickness(0, 2, 0, 2) }; RTB.Document.Blocks.Add(p); } } 

Result:

the log of beautiful palushilos

I hope that you can choose the logic of color selection depending on the content of the line.

  • Something apparently hope has let me down ... I’m writing so: string s = "First message...\nJust Second...\nThird person...\nFourth fantastic...."; if (s.Contains("First")) { AddWithColor(s, Colors.White); } else if (s.Contains("Second")) { AddWithColor(s, Colors.Green); } else if (s.Contains("Third")) { AddWithColor(s, Colors.Red); } string s = "First message...\nJust Second...\nThird person...\nFourth fantastic...."; if (s.Contains("First")) { AddWithColor(s, Colors.White); } else if (s.Contains("Second")) { AddWithColor(s, Colors.Green); } else if (s.Contains("Third")) { AddWithColor(s, Colors.Red); } string s = "First message...\nJust Second...\nThird person...\nFourth fantastic...."; if (s.Contains("First")) { AddWithColor(s, Colors.White); } else if (s.Contains("Second")) { AddWithColor(s, Colors.Green); } else if (s.Contains("Third")) { AddWithColor(s, Colors.Red); } But something doesn’t want to work - Malcolm
  • @Malcolm: No, no, no \n . Split into 4 lines, and feed them one by one, each with its own color. - VladD
  • Well, so how, if data come to me in such a format - Malcolm
  • In addition, it turns out I constantly have almost continuous data flow. - Malcolm
  • @Malcolm: Well, break by \n , what's the problem? - VladD