问题
I am having a lot of trouble getting an AvalonEdit TextEditor
to scroll to a specific line. The ScrollTo()
behavior is simply to scroll until that line is in the middle of the view. I have tried many different methods found around the internet and SO like getting the offset with
double visualTop = textEditor.TextArea.TextView.GetVisualTopByDocumentLine(line);
But each has had its own issues. For example, in the above line I was getting exceptions with the TextView.VisualLines
.
回答1:
I ended up figuring out that, since my text was all uniform height, I could just do line height * line# to get the offset. I first tried to do this using (Editor.TextArea.TextView.DocumentHeight / Editor.Document.LineCount)
to calculate the line height but that seemed to be slightly off, probably due to some floating point issues, and was increasingly off the mark the farther you went down in the document. But, again since my document is uniform height, I realized I could use the TextView.DefaultLineHeight
property and came up with:
double vertOffset = (Editor.TextArea.TextView.DefaultLineHeight) * Line;
Editor.ScrollToVerticalOffset(vertOffset);
This very consistently scrolls to exactly the right place in the document.
回答2:
Another way to do this is to set the caret position and then call BringCaretToView(). In F#:
editor.TextArea.Caret.Offset <- offset
editor.TextArea.Caret.BringCaretToView()
This will scroll the line containing 'offset' into view, but it won't scroll the text in the editor such that this line is now the first visible one. So which approach you take may depend on whether you want the target line to be at the top or not.
来源:https://stackoverflow.com/questions/39379290/avalonedit-scroll-to-line