Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 345
Christian Avatar asked Apr 26 '12 12:04

Christian


2 Answers

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.

like image 135
Behzad Avatar answered Oct 12 '22 20:10

Behzad


TextPointer myTextPointer1 = Paragraph.ContentStart.GetPositionAtOffset(20);
TextPointer myTextPointer2 = Paragraph.ContentEnd.GetPositionAtOffset(-10);

RichTextBox.Selection.Select(myTextPointer1, myTextPointer2);
           
DependencyObject currObj = RichTextBox.CaretPosition.Parent;
FrameworkElement fe = currObj as FrameworkElement;
if (fe != null)
{
    fe.BringIntoView();
}
else
{
    FrameworkContentElement fce = currObj as FrameworkContentElement;
    if (fce != null)
    {
        fce.BringIntoView();
    }
}
like image 42
jintao wu Avatar answered Oct 12 '22 18:10

jintao wu