Matthew Knudsen
Matthew Knudsen

Reputation: 213

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();
            }
        }

Upvotes: 3

Views: 4986

Answers (1)

McGarnagle
McGarnagle

Reputation: 102743

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;

Upvotes: 5

Related Questions