在 CodeBehind 中更新 FlowDocument 的文本

Update Text of FlowDocument in the CodeBehind

我需要在不更改现有格式的情况下更改 FlowDocument 的文本,但在这样做时遇到了问题。

我的想法是在文档中做一个 foreach of Blocks。然后对于任何 Paragraph 做一个 Inlinesforeach 像这样;

foreach (var x in par.Inlines)
{
    if (x.GetType() == typeof(Run))
    {
        Run r = (Run)x;
        r.Text = r.Text.Replace("@", "$");
    }
}

问题是这个returns下面的错误信息;

System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'

正确的做法是什么?

您的错误来自尝试使用 foreach 循环枚举集合,同时修改集合。使用 for 循环。

要更改流文档中的文本,请尝试使用 TextPointer + TextRange,这是一个示例(此示例会更改文本背景,但您也可以同样轻松地更改文本)。

private void ClearTextHighlight(FlowDocument haystack)
{
    TextPointer text = haystack.ContentStart;
    TextPointer tpnext = text.GetNextContextPosition(LogicalDirection.Forward);

    while (tpnext != null){
        TextRange txt = new TextRange(text, tpnext);
        //access text via txt.Text

        //apply changes like:
        var backgroundProp = txt.GetPropertyValue(TextElement.BackgroundProperty) as SolidColorBrush;

        if(backgroundProp != null && backgroundProp.Equals(Setting_HighlightColor)){
            //change is here
            txt.ApplyPropertyValue(TextElement.BackgroundProperty, Setting_DefaultColor);                
        }
        text = tpnext;
        tpnext = text.GetNextContextPosition(LogicalDirection.Forward);   
    }
}

通常的解决方案是在集合上调用 ToList() 并循环访问 ToList() 返回的新集合。

var runs =
    flowdoc.Blocks.OfType<Paragraph>()
    .SelectMany(par => par.Inlines).OfType<Run>()
    .ToList();

foreach (var r in runs)
{
    r.Text = r.Text.Replace("@", "$");
}