RichTextBlock 文本行数 [英] RichTextBlock text line count

查看:35
本文介绍了RichTextBlock 文本行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 Windows Phone 8.1 应用程序,但遇到了这个问题:

我有一个 RichTextBlock 控件来保存我的文本,如果我的控件高度大于我的屏幕,我需要在用户阅读文本时自动逐行滚动.

有没有办法确定我的 RichTextBlock 中的行数或几何计算是唯一的方法?

我尝试遍历 Blocks 集合,但似乎没有任何相关性.

我唯一带来的是使用 TextPointer.GetCharacterRect 函数:

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;}

但它不准确 - 有时它会因为 int 转换和除法而错过一两行......

任何帮助将不胜感激

解决方案

如果你在完成除法之后进行演员表,你会得到稍微更准确的计数:

var lineCount = (int)(_fatAssTextMessage.ActualHeight/lineHeight);

目前您正在将实际高度转换为整数,然后然后进行除法,这将始终低估行数.

这也偶尔会低估 - 当您看到半条线时.为确保您始终获得最大可能的价值,请执行以下操作:

var lineCount = (int)Math.Ceiling(_fatAssTextMessage.ActualHeight/lineHeight);

<块引用>

[Math.Ceiling] 返回大于或等于指定双精度浮点数的最小整数值.

来源

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

这篇关于RichTextBlock 文本行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆