title: AvalonEdit: highlight current line even when not focused
body: <p>I'm using AvalonEdit, and I want the user to always be able to see which line the caret is on, even when the editor does not have focus. To that end, I've found and adapted some code that uses a BackgroundRenderer to highlight the background of the current line.</p>
  
  <p>Unfortunately, if I change the CaretOffset while the editor isn't focused, my background rectangle stays put, on the line that was current when the editor lost focus. It doesn't sync up to the new current line until the editor gets focus again.</p>
  
  <p>I figured out <em>why</em> this is happening (just not how to fix it). Per the doc comments for IBackgroundRenderer, "Background renderer will draw only if their associated known layer chooses to draw them. For example, background renderers in the caret layer will be invisible when the caret is hidden." My background renderer lives on KnownLayer.Caret, so yes, I see why it's not updating when the editor isn't focused -- it's because the caret is hidden too. (Given that, I'm actually surprised that my rectangle stays visible.)</p>
  
  <p>I tried explicitly calling textEditor.TextArea.TextView.InvalidateLayer(KnownLayer.Caret) immediately after I set the CaretOffset, but that had no effect -- I'm guessing that the call was ignored because the caret was hidden.</p>
  
  <p><strong>What's the best way to force my current-row highlight to update even when the editor doesn't have focus?</strong></p>
  
  <hr>
  
  <p>Here's the code for my class. I'm certainly open to throwing this away and doing a different approach if there's a better way to do it.</p>
  
  <pre><code>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)));
          }
      }
  }
  </code></pre>
  
  <p>Then in my UserControl's constructor, I add the renderer to the editor:</p>
  
  <pre><code>textEditor.TextArea.TextView.BackgroundRenderers.Add(
      new HighlightCurrentLineBackgroundRenderer(textEditor));
  </code></pre>