如何实现MAUI Editor根据内部文本自动扩展高度?
解决MAUI Editor随文本自动调整高度的问题
针对你遇到的Editor无法随文本换行自动扩展高度的问题,核心问题出在父容器的固定高度限制以及未正确配置Editor的自适应属性,以下是具体解决方案:
关键修改步骤
移除ContentView的固定HeightRequest
你的ContentView设置了HeightRequest="50",这会强制容器保持固定高度,直接限制了Editor的扩展空间,必须移除这个属性。给Editor启用AutoSize属性
在Editor控件上添加AutoSize="TextChanges",这个属性会让Editor根据文本内容的变化自动调整高度,适配换行后的内容需求。确保Border不限制高度
你的Border未设置固定高度,这部分无需修改,它会自动跟随内部Editor的高度变化。
修改后的完整XAML代码
<?xml version="1.0" encoding="utf-8" ?> <ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Name="customPromptBox" x:Class="APPMAUI.Controls.PromptBox"> <Border BackgroundColor="{AppThemeBinding Light={StaticResource IcyGray}, Dark={StaticResource OffBlack}}" StrokeShape="RoundRectangle 10" Stroke="Transparent" StrokeThickness="0"> <Editor x:Name="txtPrompt" FontSize="18" Grid.Column="0" AutoSize="TextChanges" Background="Transparent" TextColor="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" Margin="10,0,20,0" Placeholder="Fai una domanda" Grid.ColumnSpan="2" /> </Border> </ContentView>
额外注意事项
- 如果该ContentView嵌套在其他布局容器(如Grid、StackLayout)中,要确保父容器没有设置固定高度或垂直方向的约束限制(比如
VerticalOptions="Start"允许扩展,而VerticalOptions="Fill"若父容器高度固定则会限制扩展)。 - 若iOS端出现高度计算不准确的情况,可以尝试在Editor的
TextChanged事件中手动同步高度:
记得在XAML中给Editor添加private void txtPrompt_TextChanged(object sender, TextChangedEventArgs e) { var editor = sender as Editor; editor.HeightRequest = editor.ContentSize.Height; }TextChanged="txtPrompt_TextChanged"事件绑定。
内容的提问来源于stack exchange,提问作者DigioMatthy
相关产品推荐
相关产品推荐

