Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight Text in WPF TextBlock

I am attempting to highlight or set the background of some selected text in a WPF TextBlock. Say I have 2 text files that I load into memory, complete a diff, and then want to diplay in a WPF App. Imagine looping through each line and then appending text to the textblock and changing color based on Deleted, inserted, or equal text.

for (int i = 0; i < theDiffs.Count; i++)
        {
            switch (theDiffs[i].operation)
            {
                case Operation.DELETE:
                    // set color to red on Source control version TextBlock
                    break;

                case Operation.INSERT:
                    WorkspaceVersion.AppendText(theDiffs[i].text);
                    // set the background color (or highlight) of appended text to green
                    break;

                case Operation.EQUAL:
                    WorkspaceVersion.AppendText(theDiffs[i].text);
                    // Set the background color (highlight) of appended text to yellow
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
like image 347
Matthew Knudsen Avatar asked May 25 '26 17:05

Matthew Knudsen


1 Answers

You'll want to append Run inline elements to the TextBlock Inlines. Eg (assuming "WorkspaceVersion" is a TextBlock):

case Operation.INSERT:
    // set the background color (or highlight) of appended text to green
    string text = theDiffs[i].text;
    Brush background = Brushes.Green;
    var run = new Run { Text = text, Background = background };
    WorkspaceVersion.Inlines.Add(run);
break;
like image 151
McGarnagle Avatar answered May 28 '26 06:05

McGarnagle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!