You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 03:09:52