gpt4 book ai didi

c# - 在 WPF TextBlock 中突出显示文本

转载 作者:行者123 更新时间:2023-11-30 14:55:42 30 4
gpt4 key购买 nike

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

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

最佳答案

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

关于c# - 在 WPF TextBlock 中突出显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24897518/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com