Search code examples
wpftextboxrichtextboxoffsetscrollviewer

Calculate offset for ScrollToVerticalOffset from line number in a WPF RichTextBox


I want to move the content of a RichTextBox to a specific line of the content. The RichTextBox provides the method ScrollToVerticalOffset from the embedded ScrollViewer. The method is documented in MSDN, but the measurement unit of the parameter named offset is not specified. The Type is double.

A VerticalOffset property of a TextBox is documented as in device-independent units (1/96th inch per unit).

So I tried to calculate the offset from the font size. The font size is given in pixels. The resulting formula is

offset = fontSize * 96 / 72  *  lineNumber;

But this jumps way behind the desired line. For now I am using this calculation:

offset = fontSize * lineNumber;

Is this correct?


Solution

  • It is true that long time passes from asking this question, but still have not found the right answer to it !!

    I used this code now, that's good for me really:

    var offset = (lineNumber * (fontSize + 2)) - richTextBox.ActualHeight / 2;
    richTextBox.ScrollToVerticalOffset(offset);
    

    If you know one solution better than this way, please help me.