UWP:RichEditBox 的高度计算错误

UWP: Wrong computation of height for 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 中写入的任何文本,方法 returns 元素的正确高度。 但是当我的文本只覆盖一行时,结果总是高度几乎是正确结果的两倍。

请在此处找到重现该问题的 MVC:https://github.com/cghersi/UWPExamples/tree/master/SizeOfTextBox

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

RichEditBox的默认高度是32px,也就是说当你的实际高度小于32时,它仍然显示32。而且在样式中,控制内容的高度是Border,所以你应该改变Border的MinHeight。另外,你可以去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>