Kal*_*xey 5 wpf textblock fixeddocument line-count
我有FixedDocument
页面,我想TextBlock
放在它上面,但它可能Textblock
不适合页面的高度。
所以我想从繁重的产生线TextBlock
带TextWrapping
,然后创建新的TextBlock
,即通过安装高度,并把它页。
TextBlock
有LineCount
私有财产,这意味着它TextLines
在包装后有,我可以以某种方式得到它。使用运行
创建TextBlock
:
public TextItem(PageType pageType, Run[] runs, Typeface typeFace, double fontSize)
: base(pageType)
{
this.TextBlock = new TextBlock();
this.TextBlock.Inlines.AddRange(runs);
if (typeFace != null)
this.TextBlock.FontFamily = typeFace.FontFamily;
if (fontSize > 0)
this.TextBlock.FontSize = fontSize;
this.TextBlock.TextWrapping = TextWrapping.Wrap; //wrapping
}
Run Code Online (Sandbox Code Playgroud)
TextBlock
用文本创建:
public TextItem(PageType pageType, String text, Typeface typeFace, double fontSize)
: base(pageType)
{
if (typeFace == null || fontSize == 0)
throw new Exception("Wrong textitem parameters");
this.TextBlock = new TextBlock();
this.TextBlock.Text = text;
this.TextBlock.FontFamily = typeFace.FontFamily;
this.TextBlock.FontSize = fontSize;
this.TextBlock.TextWrapping = TextWrapping.Wrap;
this.TextBlock.TextAlignment = TextAlignment.Justify;
this.TypeFace = typeFace;
}
Run Code Online (Sandbox Code Playgroud)
将宽度设置为TextBlock
并获取DesiredSize
:
this.TextBlock.Width = document.CurrentPage.Content.ActualWidth;
this.TextBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
Run Code Online (Sandbox Code Playgroud)
我面临着完全相同的问题,有一段时间,我失去了希望,我认为没有解决办法。
但是,我错了,有很多解决方案(至少三个),
你是对的,其中之一LineCount
通过使用反射来使用该属性。
第二个使用它自己的算法来获取线条。
第三个是我更喜欢的,它有非常优雅的方式来获得你想要的结果。
请参考这个问题,看看这个问题的三个答案。
根据TextWrapping属性获取TextBlock的行数?
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);
}
}
Run Code Online (Sandbox Code Playgroud)