.NET8 MAUI横竖屏切换UI不刷新,iOS/Android如何强制刷新?
.NET 8 MAUI 横竖屏切换后强制刷新UI方案
iOS 平台处理方式
重写页面的ViewWillTransitionToSize方法,在设备方向变化时触发UI刷新:
using UIKit; using Microsoft.Maui.Platform; public partial class YourPage : ContentPage { protected override void OnHandlerChanged() { base.OnHandlerChanged(); if (Handler?.PlatformView is UIKit.UIViewController viewController) { viewController.ViewWillTransitionToSize += ViewController_ViewWillTransitionToSize; } } private void ViewController_ViewWillTransitionToSize(object sender, UIKit.UIViewControllerTransitionToSizeEventArgs e) { // 强制刷新页面布局 this.ForceLayout(); // 若存在数据绑定,可重置绑定上下文同步数据 this.BindingContext = this.BindingContext; } protected override void OnDisappearing() { if (Handler?.PlatformView is UIKit.UIViewController viewController) { viewController.ViewWillTransitionToSize -= ViewController_ViewWillTransitionToSize; } base.OnDisappearing(); } }
Android 平台处理方式
利用Android的ConfigurationChanged事件,在方向变化时触发UI刷新:
using Android.Content; using Microsoft.Maui.Platform; public partial class YourPage : ContentPage { protected override void OnHandlerChanged() { base.OnHandlerChanged(); if (Handler?.PlatformView is Android.App.Activity activity) { activity.ConfigurationChanged += Activity_ConfigurationChanged; } } private void Activity_ConfigurationChanged(object sender, Android.Content.Res.ConfigurationChangedEventArgs e) { // 强制刷新页面布局 this.ForceLayout(); // 若存在数据绑定,可重置绑定上下文同步数据 this.BindingContext = this.BindingContext; } protected override void OnDisappearing() { if (Handler?.PlatformView is Android.App.Activity activity) { activity.ConfigurationChanged -= Activity_ConfigurationChanged; } base.OnDisappearing(); } }
通用补充方案
- 若页面包含
CollectionView或ListView等列表控件,可单独刷新控件数据源:
// 假设你的CollectionView名为MyCollectionView MyCollectionView.ItemsSource = MyCollectionView.ItemsSource;
- 调用页面的
InvalidateMeasure方法,触发重新测量布局:
this.InvalidateMeasure();
内容的提问来源于stack exchange,提问作者Enrico
相关产品推荐
相关产品推荐

