在 rtb 中格式化文本时,我的性能很差:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button Click="ApplyFormatClick">ApplyFormat</Button>
<TextBlock x:Name="Time"/>
</StackPanel>
<RichTextBox x:Name="Rtb" Grid.Row="1">
<RichTextBox.Document>
<FlowDocument>
<Paragraph>
<Run>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</Run>
</Paragraph>
</FlowDocument>
</RichTextBox.Document>
</RichTextBox>
</Grid>
后面的代码:
private readonly SolidColorBrush _blueBrush = Brushes.Blue;
private void ApplyFormatClick(object sender, RoutedEventArgs e)
{
Stopwatch stopwatch = Stopwatch.StartNew();
FlowDocument doc = Rtb.Document;
TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.ClearAllProperties();
int i = 0;
while (true)
{
TextPointer p1 = range.Start.GetPositionAtOffset(i);
i++;
TextPointer p2 = range.Start.GetPositionAtOffset(i);
if (p2 == null)
break;
TextRange tempRange = new TextRange(p1, p2);
tempRange.ApplyPropertyValue(TextElement.ForegroundProperty, _blueBrush);
tempRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
i++;
}
Time.Text = "Formatting took: " + stopwatch.ElapsedMilliseconds + " ms, number of characters: " + range.Text.Length;
}
应用格式需要一秒钟,在对其进行分析时,罪魁祸首是:
tempRange.ApplyPropertyValue(TextElement.ForegroundProperty, _blueBrush);
tempRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
探查器结果对我来说非常不透明。
我以前从未使用过FlowDocument
,RichTextBox
所以我可能做错了。
最终结果类似于 VS 查找替换,它将基于可编辑的正则表达式突出显示文本中的匹配项。
有什么不同的方法可以加快速度?(Github 上的示例)