我将尝试为WPF RichTextBox显示基本语法高亮。虽然它基本上能够工作,但渲染性能非常差。
首先,我尝试了以下代码:
/// <summary>
/// Main event handler for syntax highlighting.
/// </summary>
private void XmlChanged(object sender, TextChangedEventArgs e)
{
VM.Dirty = true;
if (VM.Pretty)
{
var range = new TextRange(XmlView.Document.ContentStart, XmlView.Document.ContentEnd);
Render(range.Text);
}
}
/// <summary>
/// Entry point for programmatically resetting the textbox contents
/// </summary>
private void Render(string text)
{
XmlView.TextChanged -= this.XmlChanged;
if (VM.Pretty)
{
var tokens = tokenizer.Tokenize(text);
Format(XmlView.Document, tokens);
}
XmlView.TextChanged += this.XmlChanged;
}
private void Format(FlowDocument doc, List<Token> tokens)
{
var start = doc.ContentStart;
foreach (var token in tokens)
{
TextRange range = new TextRange(start.GetPositionAtOffset(token.StartPosition, LogicalDirection.Forward),
start.GetPositionAtOffset(token.EndPosition, LogicalDirection.Forward));
range.ApplyPropertyValue(TextElement.ForegroundProperty, m_syntaxColors[token.Type]);
}
}
对于一个仅含有100多个标记的2KB文档进行测试,每次按键后重绘需要1-2秒钟,这显然是无法接受的。经过分析,我发现我的词法分析器比Format()函数快了几个数量级。因此,我尝试了一些双缓冲技术:
private void Render(string text)
{
XmlView.TextChanged -= this.XmlChanged;
// create new doc offscreen
var doc = new FlowDocument();
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.Text = text;
if (VM.Pretty)
{
var tokens = tokenizer.Tokenize(text);
Format(doc, tokens);
}
// copy to active buffer
var stream = new MemoryStream(65536);
range.Save(stream, DataFormats.XamlPackage);
var activeRange = new TextRange(XmlView.Document.ContentStart, XmlView.Document.ContentEnd);
activeRange.Load(stream, DataFormats.XamlPackage);
XmlView.TextChanged += this.XmlChanged;
}
基准测试表明,将Format()渲染到屏幕外会稍微快一些,但现在感知性能更差了!
这该怎么办?