Home > Software engineering >  using C# Format colour of line in RichTextBox based on the content of the string
using C# Format colour of line in RichTextBox based on the content of the string

Time:10-28

I am using C# for the first time and my goal is to create an application that outputs text to a window. The windows structure is defined in a .XAML file and the text in question is to be added to a RichTextBox. Depending on the content of the string to be appended I want the text color to be different. I.E if the string contains the word "passed" I want the text to be green and red if it contains "failed". I have found a method that almost works but instead changes the color of all the text in the box instead of just the desired line.

The name of the RichTextBox is "TextResults" as shown below: enter image description here

I have used the ForeGround property and assigned it to a SolidColorBrush object

                    if (dispText[1].Contains("passed")) textResults.Foreground = new SolidColorBrush(Colors.Green);
                    else if (dispText[1].Contains("failed")) textResults.Foreground = new SolidColorBrush(Colors.Red);
                    else textResults.Foreground = new SolidColorBrush(Colors.Black);

                    textScript.AppendText(dispText[0]   Environment.NewLine);
                    textResults.AppendText(dispText[1]   Environment.NewLine);

The problem is, this method applies the color to all strings in the RichTextBox, so assuming the final string contains "failed", all the text goes red. Output

I have looked online at lots of different methods and none seem to help, this is my first stack overflow post so apologies if I have committed any sins in this post. Any help would be much appreciated.

CodePudding user response:

The extension method used to color a new added line:

using System;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace WpfApp7
{
    public static class RichTextBoxExt
    {
        public static void ColorLine(this RichTextBox rtb, string text)
        {
            if (rtb.Document.Blocks.LastBlock is Paragraph par)
            {
                Brush brush = rtb.Foreground; // Default
                if (text.Contains("passed"))
                {
                    brush = Brushes.Green;
                }
                else if (text.Contains("failed"))
                {
                    brush = Brushes.Red;
                }
                par.Inlines.Add(new Run(text   Environment.NewLine) { Foreground = brush });
            }
        }
    }
}

MainWindow.xaml.cs:

using System;
using System.Windows;

namespace WpfApp7
{  
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Color line
            rtb.ColorLine(tbox.Text);

            // Clean the text box
            tbox.Text = String.Empty;
        }
    }
}

MainWindow.xaml:

<Window x:Class="WpfApp7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="500">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>            
        </Grid.RowDefinitions>
        <RichTextBox Grid.Row="0" x:Name="rtb" AllowDrop="True" VerticalScrollBarVisibility="Auto" Padding="2" />

        <Grid Grid.Row="1"  >
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="auto"/>
            </Grid.ColumnDefinitions>
            <TextBox x:Name="tbox" Margin="3"></TextBox>
            <Button Grid.Column="1" Click="Button_Click" Margin="3"> Add a new line </Button>
        </Grid>
    </Grid>
</Window>

CodePudding user response:

public static class WpfHelperExtensions
{
    public static void AppendColoredText(this RichTextBox box, string text, Color color)
    {
        var range = new TextRange(box.Document.ContentEnd, box.Document.ContentEnd)
        {
            Text = text
        };
        range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(color));
        box.ScrollToEnd();
    }
}

Usage

if (dispText[1].Contains("passed")) 
    textResults.AppendColoredText(dispText[1], new SolidColorBrush(Colors.Green));
else if (dispText[1].Contains("failed")) 
    textResults.AppendColoredText(dispText[1], new SolidColorBrush(Colors.Red));
else 
    textResults.AppendColoredText(dispText[1], new SolidColorBrush(Colors.Black));
  • Related