gpt4 book ai didi

c# - 突出显示 FlowDocument 中的部分文本

转载 作者:太空狗 更新时间:2023-10-29 23:15:31 25 4
gpt4 key购买 nike

我想根据搜索结果突出显示 FlowDocument 中的某些文本部分。我正在做的是在 FlowDocument 的文本中获取搜索词出现的索引,然后在文本范围内应用背景颜色,从找到的索引开始,到找到的索引 + 搜索词长度结束.

TextRange content = new TextRange(myFlowDocument.ContentStart, 
myFlowDocument.ContentEnd);
List<int> highlights = GetHighlights(content.Text, search);

foreach (int index in highlights)
{
var start = myFlowDocument.ContentStart;
var startPos = start.GetPositionAtOffset(index);
var endPos = start.GetPositionAtOffset(index + search.Length);
var textRange = new TextRange(startPos, endPos);
textRange.ApplyPropertyValue(TextElement.BackgroundProperty,
new SolidColorBrush(Colors.Yellow));
}

TextRange newRange = new TextRange(myFlowDocument.ContentStart,
newDocument.ContentEnd);
FlowDocument fd = (FlowDocument)XamlReader.Parse(newRange.Text);

问题是,我正在文档文本中搜索索引,但是当我返回 FlowDocument 时,添加了 xaml 标签并且我看到高亮显示被移动了。我该如何解决?

最佳答案

最后,受到 user007 的启发,在进行一些修改后,我设法突出显示了 FlowDocument 中出现的所有字符串。这是我的代码:

for (TextPointer position = newDocument.ContentStart;
position != null && position.CompareTo(newDocument.ContentEnd) <= 0;
position = position.GetNextContextPosition(LogicalDirection.Forward))
{
if (position.CompareTo(newDocument.ContentEnd) == 0)
{
return newDocument;
}

String textRun = position.GetTextInRun(LogicalDirection.Forward);
StringComparison stringComparison = StringComparison.CurrentCulture;
Int32 indexInRun = textRun.IndexOf(search, stringComparison);
if (indexInRun >= 0)
{
position = position.GetPositionAtOffset(indexInRun);
if (position != null)
{
TextPointer nextPointer = position.GetPositionAtOffset(search.Length);
TextRange textRange = new TextRange(position, nextPointer);
textRange.ApplyPropertyValue(TextElement.BackgroundProperty,
new SolidColorBrush(Colors.Yellow));
}
}
}

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

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