如何在渲染之前测量 WPF 中 TextBlock 的大小?
我有一个 WPF DataTemplate,其中有两个 TextBlock 控件(堆叠),下面还有一些其他元素。由于一些复杂的布局代码,我需要知道两个 TextBlock 元素的高度,以便我可以绘制一些奇特的连接线,并排列其他控件等。
如果我知道要进入 TextBlock 的文本,我就知道字体等,是否有某种方法可以计算或测量这些 TextBlock 的高度而不实际渲染它们?
I have a WPF DataTemplate with two TextBlock controls (stacked) and then some other elements underneath. Due to some complicated layout code, I need to know the height of the two TextBlock elements so that I can draw some fancy connector lines, and line up other controls, etc.
If I know the text that's going into the TextBlocks, and I know the font, etc., is there some way I can compute or measure the height of these TextBlocks without actually rendering them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为调用
UIElement 就足够了.Measure(Size)
方法,然后检查UIElement.DesiredSize
属性。有关详细信息,请查看提供的 MSDN 链接。I think it should be sufficient to call the
UIElement.Measure(Size)
method and subsequently check theUIElement.DesiredSize
property. For more information, check the provided MSDN links.对
UIElement.Measure(Size)
的调用将Size
作为参数。第二次调用UIElement.DesiredSize
返回您传递到Measure
方法中的任何Size
。我认为是这种情况,因为
UIElement
(在本例中为TextBlock
)还不是任何控件的子级,因此DesiredSize
没有有理由变得不同。The call to
UIElement.Measure(Size)
, takes as a parameterSize
. The second callUIElement.DesiredSize
returns whateverSize
you passed into theMeasure
method.I think this is the case because
UIElement
(TextBlock
in this case) is NOT a child of any control (yet) and thereforeDesiredSize
has no reason to be anything different.我知道这是一个相当老的问题,但我发现使用以下代码
dsrdSize 返回为 {47.05,15.96}。
诀窍似乎是使 msrSize 大于预期的实际大小。 msrSize 似乎充当 DesiredSize() 结果的限制。
例如,使用 msrSize = new Size(10, 10) 会导致 dsrdSize 为 {10,10}。
希望这对某人有帮助。
I appreciate that this is a rather old question, but I have found that using the following code
dsrdSize is returned as {47.05,15.96}.
The trick seems to be making the msrSize larger than the expected actual size. msrSize seems to act as a limit for the DesiredSize() result.
For example, using msrSize = new Size(10, 10), results in a dsrdSize of {10,10} here.
Hope this helps someone.
由于 Measure 是在 UIElement 中定义的,因此您可以测量任何 UIElement 派生对象(包括 TextBlock)的形状:
And since Measure is defined in UIElement you can measure the shape of any UIElement derived object including TextBlock: