.NET Maui中如何根据字体大小动态截断Label文本
问题:动态适配字体大小的Label文本截断
我有一个包含Label的Grid控件,该Label的字体大小可变,可显示的行数会随字体大小变化——字体越大,可显示行数越少。目前最右侧列的文本被容器部分截断,我希望能根据Label可显示的行数动态截断文本,而非通过显式设置Label的MaxLines和LineBreakMode属性(该方式需固定值,无法适配字体大小变化)。我使用XAML定义UI,也接受C#解决方案。
已尝试的XAML代码及效果(基于.NET Maui 9.0.70,Android设备测试)
0. 原始XAML
<Grid BackgroundColor="Orange" WidthRequest="190" HeightRequest="250"> <Label FontSize="32" TextColor="Black" Text="This is a label that has a lot of text. It is intentionally long so that it will line wrap and eventually spill over the edge." /> </Grid>
效果:文本自动换行,但超出Grid高度的部分被截断,无省略号。
1. 未设置Label高度和MaxLines
<Grid BackgroundColor="Orange" WidthRequest="190" HeightRequest="250"> <Label FontSize="32" TextColor="Black" Text="This is a label that has a lot of text. It is intentionally long so that it will line wrap and eventually spill over the edge." LineBreakMode="TailTruncation" /> </Grid>
效果:仅渲染1行文本,尾部添加省略号,未利用Grid的垂直空间。
2. 设置HeightRequest
<Grid BackgroundColor="Orange" WidthRequest="190" HeightRequest="250"> <Label FontSize="32" TextColor="Black" Text="This is a label that has a lot of text. It is intentionally long so that it will line wrap and eventually spill over the edge." LineBreakMode="TailTruncation" HeightRequest="150" /> </Grid>
效果:文本垂直居中,但仍仅显示1行,尾部截断。
3. 设置VerticalOptions="Fill"
<Grid BackgroundColor="Orange" WidthRequest="190" HeightRequest="250"> <Label FontSize="32" TextColor="Black" Text="This is a label that has a lot of text. It is intentionally long so that it will line wrap and eventually spill over the edge." LineBreakMode="TailTruncation" VerticalOptions="Fill" /> </Grid>
效果:文本顶部对齐,仅显示1行,尾部截断,未填满Grid垂直空间。
内容的提问来源于stack exchange,提问作者Victor Chelaru
相关产品推荐
相关产品推荐

