简体   繁体   中英

RichTextBlock text line count

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM