突出显示FlowDocument中的部分文本

kzu*_*zub 5 c# wpf highlight flowdocument

我想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);
Run Code Online (Sandbox Code Playgroud)

问题是,我正在搜索文档文本中的索引,但是当我返回时,FlowDocument添加了xaml标记,并且我看到了突出显示的内容.我该如何解决?

use*_*007 3

您需要迭代 usingGetNextContextPosition(LogicalDirection.Forward)和 get TextPointer,将 this 与 previous 一起使用TextPointer来构造TextRange。在这一点上TextRange你可以应用你的逻辑。

\n\n

您不能做的是使用单个 TextRange 来FlowDocument搜索文本。FlowDocument不仅仅是文字:

\n\n
    private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        String search = this.content.Text;\n\n        TextPointer text = doc.ContentStart;\n        while (true)\n        {\n            TextPointer next = text.GetNextContextPosition(LogicalDirection.Forward);\n            if (next == null)\n            {\n                break;\n            }\n            TextRange txt = new TextRange(text, next);\n\n            int indx = txt.Text.IndexOf(search);\n            if (indx > 0)\n            {\n                TextPointer sta = text.GetPositionAtOffset(indx);\n                TextPointer end = text.GetPositionAtOffset(indx + search.Length);\n                TextRange textR = new TextRange(sta, end);\n                textR.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));\n            }\n            text = next;\n        }\n    }\n
Run Code Online (Sandbox Code Playgroud)\n\n

更新:\nit 并不总是有效,例如,如果您有列表,特殊字符 (\\t) 会被计算在内IndexOf,但GetPositionAtOffset不会将它们计入:

\n\n
\xe2\x80\xa2   ListItem 1\n\xe2\x80\xa2   ListItem 2\n\xe2\x80\xa2   ListItem 3\n
Run Code Online (Sandbox Code Playgroud)\n\n

这一行:

\n\n
int indx = txt.Text.IndexOf(search);\n
Run Code Online (Sandbox Code Playgroud)\n\n

可以替换为:

\n\n
int indx = Regex.Replace(txt.Text, \n     "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled).IndexOf(search);\n
Run Code Online (Sandbox Code Playgroud)\n