2

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

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

4

1 回答 1

2

RichEditBox 的默认高度是 32px,也就是说当你的实际高度小于 32 时,它仍然显示 32。而且在 style 中,控制内容的高度是 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>
于 2019-09-09T08:38:50.313 回答