我正在使用 AvalonEdit,我希望用户始终能够看到插入符号在哪一行,即使编辑器没有焦点。为此,我找到并改编了一些使用 BackgroundRenderer 突出当前行背景的代码。
不幸的是,如果我在编辑器没有聚焦时更改 CaretOffset,我的背景矩形会保持在编辑器失去焦点时的当前行上。在编辑器再次获得焦点之前,它不会同步到新的当前行。
我弄清楚了为什么会发生这种情况(只是不知道如何解决它)。根据 IBackgroundRenderer 的文档注释,“背景渲染器仅在其关联的已知层选择绘制它们时才会绘制。例如,当插入符号隐藏时,插入符号层中的背景渲染器将不可见。” 我的背景渲染器存在于 KnownLayer.Caret 上,所以是的,我明白了为什么当编辑器没有聚焦时它没有更新——这是因为插入符号也被隐藏了。(考虑到这一点,我真的很惊讶我的矩形仍然可见。)
我尝试在设置 CaretOffset 后立即显式调用 textEditor.TextArea.TextView.InvalidateLayer(KnownLayer.Caret) ,但这没有任何效果——我猜该调用被忽略了,因为插入符号被隐藏了。
即使编辑器没有焦点,强制我的当前行突出显示更新的最佳方法是什么?
这是我的课程的代码。如果有更好的方法,我当然愿意放弃它并采取不同的方法。
public class HighlightCurrentLineBackgroundRenderer : IBackgroundRenderer
{
private TextEditor _editor;
public HighlightCurrentLineBackgroundRenderer(TextEditor editor)
{
_editor = editor;
}
public KnownLayer Layer
{
get { return KnownLayer.Caret; }
}
public void Draw(TextView textView, DrawingContext drawingContext)
{
if (_editor.Document == null)
return;
textView.EnsureVisualLines();
var currentLine = _editor.Document.GetLineByOffset(_editor.CaretOffset);
foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, currentLine))
{
drawingContext.DrawRectangle(
new SolidColorBrush(Color.FromArgb(0x40, 0, 0, 0xFF)), null,
new Rect(rect.Location, new Size(textView.ActualWidth - 32, rect.Height)));
}
}
}
然后在我的 UserControl 的构造函数中,我将渲染器添加到编辑器中:
textEditor.TextArea.TextView.BackgroundRenderers.Add(
new HighlightCurrentLineBackgroundRenderer(textEditor));