布局文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp3.MainPage">
<ScrollView x:Name="myScllView">
<StackLayout
x:Name="vtlStackLyt"
Spacing="25"
Padding="30,0"
Background="red"
VerticalOptions="Center">
<Image
Source="dotnet_bot.png"
SemanticProperties.Description="Cute dot net bot waving hi to you!"
HeightRequest="200"
HorizontalOptions="Center" />
<Image
Source="dotnet_bot.png"
SemanticProperties.Description="Cute dot net bot waving hi to you!"
HeightRequest="200"
HorizontalOptions="Center" />
<Label
Text="Hello, World!"
SemanticProperties.HeadingLevel="Level1"
FontSize="32"
HorizontalOptions="Center" />
<Label
x:Name="lblText"
Text="{Binding MyLabelText}"
SemanticProperties.HeadingLevel="Level2"
SemanticProperties.Description="Welcome to dot net Multi platform App U I"
FontSize="18"
HorizontalOptions="Center" />
<Button
x:Name="CounterBtn"
Text="Click me"
SemanticProperties.Hint="Counts the number of times you click"
Clicked="OnCounterClicked"
HorizontalOptions="Center" />
</StackLayout>
</ScrollView>
</ContentPage>
上述布局文件是使用 VS 创建 iOS 平台下的 MAUI 项目自动生成的。在 cs 代码中对 Label lblText 赋值一个大文本以后,外层的 ScrollView 不能显示全部内容,也就是说 ScrollView 无法自适应子控件内容变化后的高度。代码如下:
private void OnCounterClicked(object sender, EventArgs e)
{
// 主线程更新 ui
MainThread.BeginInvokeOnMainThread(() =>
{
// 大文本,显示时会换行,超出原始高度
strDemo = "Demo demo demo demo demo demo demo demo demo demo demo demo demo
demo demo demo demo demo demo demo demo demo demo demo demo demo
demo demo demo demo demo demo demo demo demo .............";
// 把大文本字符串赋值给绑定对象,呈现在页面
viewModel.MyLabelText = $"Clicked {strDemo} time";
});
}
网上说了很多方案,什么计算高度、调用 ForceLayout 方法等,都是坑。在百试不灵后,尝试 Home 键退回桌面,再进入 app 发现,ScrollView 居然正常了。也就是说,ScrollView 已经自适应了高度,只是视图没有刷新。于是调用页面级别的 InvalidateMeasure 方法后,成功实现了视图刷新。
代码修改后如下:
private void OnCounterClicked(object sender, EventArgs e)
{
// 主线程更新 ui
MainThread.BeginInvokeOnMainThread(() =>
{
// 大文本,显示时会换行,超出原始高度
strDemo = "Demo demo demo demo demo demo demo demo demo demo demo demo demo
demo demo demo demo demo demo demo demo demo demo demo demo demo
demo demo demo demo demo demo demo demo demo .............";
// 把大文本字符串赋值给绑定对象,呈现在页面
viewModel.MyLabelText = $"Clicked {strDemo} time";
// 当前页面 MainPage 的实例对象
this.InvalidateMeasure();
});
}