如何应用TextWrapping之后如何获取TextBlock行?

问题描述 投票:0回答:1

我正在试图在包含TextBlock的几页上拆分一个很长的字符串(文档),但是,我需要使每一页具有特定的行数,这意味着我需要将TextBlock拆分成几行。

[我试图创建几种逻辑,但没有获得准确的结果的运气,但是在这里找到了一个解决方案(Get the lines of the TextBlock according to the TextWrapping property?),该解决方案在我的原型项目上为我工作,然后停止工作,并在一行中获得了全部文本。

这里是上述主题的代码:

public static class TextUtils
    {
        public static IEnumerable<string> GetLines(this TextBlock source)
        {
            var text = source.Text;
            int offset = 0;
            TextPointer lineStart = source.ContentStart.GetPositionAtOffset(1, LogicalDirection.Forward);
            do
            {
                TextPointer lineEnd = lineStart != null ? lineStart.GetLineStartPosition(1) : null;
                int length = lineEnd != null ? lineStart.GetOffsetToPosition(lineEnd) : text.Length - offset;
                yield return text.Substring(offset, length);
                offset += length;
                lineStart = lineEnd;
            }
            while (lineStart != null);
        }
    }

这是我的代码:

<TextBlock x:Name="testTB" TextAlignment="Justify" FontFamily="Arial" FontSize="12" TextWrapping="Wrap" Width="100"/>
testTB.Text = Functions.GenString(200);

foreach (string xc in testTB.GetLines())
{
    MessageBox.Show(xc);
}

我猜测问题出在lineStart.GetLineStartPosition(1)返回null

感谢您的帮助,在此先感谢。

c# wpf textblock
1个回答
0
投票

对我来说,您发布的代码看起来容易出错。当您使用InlineBold之类的Underline元素时,您将不再具有纯文本,而是诸如内联元素的标签之类的上下文标记。我猜这是基于偏移的string.Substrting失败的地方。解决方案是从检索到的TextRange创建一个TextPointer,然后通过TextRange.Text属性提取纯文本:

© www.soinside.com 2019 - 2024. All rights reserved.