我需要根据内容计算 RichEditBox 的确切高度。为此,我使用以下方法,无论如何证明都可以,但是当文本是一行时!
public static double GetElemHeight(FrameworkElement elem, double? actualWidth = null)
{
if (elem == null)
return 0;
// take note of the existing height, if any, since we have to re-establish it later:
double currentH = elem.Height;
if (!double.IsNaN(currentH))
elem.Height = double.NaN;
double totalW = (actualWidth ?? elem.Width) + elem.Margin.Left + elem.Margin.Right;
// Measure() only works as expected in this context if the Height is NaN:
elem.Measure(new Size(totalW, Double.PositiveInfinity));
Size size = elem.DesiredSize;
elem.Height = currentH; //re-establish the correct height
return size.Height - elem.Margin.Top - elem.Margin.Bottom;
}
基本上发生的情况是,对于在 RichEditBox 中写入的任何文本,该方法都会返回元素的正确高度。但是当我的文本只覆盖一行时,结果总是高度几乎是正确结果的两倍。
请在此处找到重现问题的 MVC:https ://github.com/cghersi/UWPExamples/tree/master/SizeOfTextBox
关于我做错了什么的任何线索?