UWP:RichEditBox 的高度计算错误



我需要根据其内容计算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

关于我做错了什么的任何线索?

RichEditBox 的默认高度为 32px,这意味着当您的实际高度小于 32 时,它仍然显示 32。在样式上,控制内容的高度是边框,因此您应该更改边框的最小高度。此外,你可以去 generic.xaml 获取 RichEditBox 的样式。

<Page.Resources>
<Style TargetType="RichEditBox">
......
<Setter Property="SelectionFlyout" Value="{StaticResource TextControlCommandBarSelectionFlyout}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RichEditBox">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<VisualStateManager.VisualStateGroups>
......
</VisualStateManager.VisualStateGroups>
......
<Border x:Name="BorderElement" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="{TemplateBinding CornerRadius}" MinHeight="0" MinWidth="{ThemeResource TextControlThemeMinWidth}" Grid.RowSpan="1" Grid.Row="1"/>
......
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>

相关内容

  • 没有找到相关文章

最新更新