在WPF TextBlock中突出显示文本

3
我试图在WPF TextBlock中突出显示或设置一些选定文本的背景。 假设我有2个文本文件,我将它们加载到内存中,完成差异比较,然后想在WPF应用程序中显示。想象一下循环遍历每一行,然后将文本追加到TextBlock并根据删除、插入或相同的文本更改颜色。
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();
            }
        }
1个回答

5
你需要将Run行内元素附加到TextBlock Inlines中。例如(假设“WorkspaceVersion”是一个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;

太棒了!谢谢! - Matthew Knudsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接