在代码隐藏中更新流文档的文本



我需要在不更改现有格式的情况下更改FlowDocument的文本,并且无法执行此操作。

我的想法是在文档中做一个foreachBlocks。然后对于任何Paragraph像这样对Inlines进行foreach;

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

问题是这会返回以下错误消息;

System.InvalidOperationException:"集合已修改;枚举操作可能无法执行。

正确的方法是什么?

通常的解决方案是在集合上调用 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("@", "$");
}

错误来自尝试使用 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);   
}
}

最新更新