我需要在不更改现有格式的情况下更改FlowDocument
的文本,但在这样做时遇到了问题。
我的想法是在文档中做一个Blocks
的foreach
。然后,对于任何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:‘集合已修改;可能无法执行枚举操作。’
这样做的正确方法是什么?
发布于 2018-06-01 03:00:10
通常的解决方案是在集合上调用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("@", "$");
}
发布于 2018-06-01 02:39:26
您的错误来自于尝试在修改集合的同时使用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);
}
}
https://stackoverflow.com/questions/50630269
复制相似问题