问题
I am working on Windows Phone 8.1 application and I got this issue:
I have a RichTextBlock
control which holds my text, if my control height is bigger than my screen I need to scroll line by line automaticly while the user reads the text.
Is there any way to determine the number of the lines in my RichTextBlock
or geometric calculation is the only way?
I've tried to iterate over the Blocks collection, but nothing seems to be relevant.
The only thing that I've came with is by using TextPointer.GetCharacterRect
function:
if(msgContainer.Blocks.Any())
{
var item = msgContainer.Blocks.FirstOrDefault();
var height = item.LineHeight;
var startRect = item.ContentStart.GetCharacterRect(LogicalDirection.Forward);
var lineHeight = startRect.Height;
var lineCount = (int)_fatAssTextMessage.ActualHeight / lineHeight;
}
But it isn't accurate - sometimes it misses by line or two since the int casting, and the division...
Any help will be appreciated
回答1:
You'll get a slightly more accurate count if you do the cast after you've done the division:
var lineCount = (int)(_fatAssTextMessage.ActualHeight / lineHeight);
Currently you are casting the actual height to an integer and then doing the division which will always undercount the number of lines.
This will also undercount occasionally - when you have half a line visible. To ensure you always get the largest possible value do something like this:
var lineCount = (int)Math.Ceiling(_fatAssTextMessage.ActualHeight / lineHeight);
[
Math.Ceiling
] Returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.
Source
来源:https://stackoverflow.com/questions/34412421/richtextblock-text-line-count