【问题标题】:Highlight Text in WPF TextBlock突出显示 WPF TextBlock 中的文本
【发布时间】:2014-07-22 20:46:37
【问题描述】:

我正在尝试突出显示或设置 WPF TextBlock 中某些选定文本的背景。 假设我有 2 个文本文件加载到内存中,完成一个差异,然后想要在 WPF 应用程序中显示。想象一下循环遍历每一行,然后将文本附加到文本块并根据已删除、插入或相等的文本更改颜色。

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

【问题讨论】:

    标签: c# wpf xaml textblock


    【解决方案1】:

    您需要将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;
    

    【讨论】:

    • 太棒了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2011-01-15
    • 2015-05-29
    相关资源
    最近更新 更多