【问题标题】:How to get the HEIGHT of the Run or Paragraph如何获得运行或段落的高度
【发布时间】:2013-04-05 09:14:18
【问题描述】:
我在FlowDocument 中找到了Run 或Paragraph,现在我需要知道它的高度。
即
while (navigator.CompareTo(flowDocViewer.Document.ContentEnd) < 0)
{
TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);
Run run = navigator.Parent as Run;
// I need to get HEIGHT of Run in pixels somehow
事实上有可能吗?
谢谢!
【问题讨论】:
标签:
c#
.net
wpf
height
flowdocument
【解决方案1】:
我正在使用的一个小功能。输入是一个包含 Section 的字符串。您可以轻松渲染其他块元素,例如段落。
您也可以省略 Parse 方法的第二个参数。
诀窍不是测量段落,而是测量包含 RichTextBox 的 ViewBox。这是实际呈现 Flowdocument 所必需的。 ViewBox 动态获取 rtb 的大小。也许你甚至可以在没有 ViewBox 的情况下做到这一点。我花了一些时间来解决这个问题,它对我有用。
请注意,RichTextBox 中的 Width 设置为 double.MaxValue。这意味着当您要测量单个段落时,它必须非常长,否则所有内容都在一行中。所以这只有在你知道输出设备的宽度时才有意义。因为这是一个 FlowDocument,所以没有宽度,它会流动;)
我用它来对我知道纸张大小的 FlowDocument 进行分页。
返回的高度是与设备无关的单位。
private double GetHeaderFooterHeight(string headerFooter)
{
var section = (Section)XamlReader.Parse(headerFooter, _pd.ParserContext);
var flowDoc = new FlowDocument();
flowDoc.Blocks.Add(section);
var richtextbox = new RichTextBox { Width = double.MaxValue, Document = flowDoc };
var viewbox = new Viewbox { Child = richtextbox };
viewbox.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
viewbox.Arrange(new Rect(viewbox.DesiredSize));
var size = new Size() { Height = viewbox.ActualHeight, Width = viewbox.ActualWidth };
return size.Height;
}