MAUI 调整活动规模

Max*_*der 4 window-resize maui

我正在尝试使用 MAUI 作为 Windows 应用程序,该应用程序需要在从宽屏幕到平板电脑的多种屏幕尺寸上工作,并允许调整窗口大小。

我需要能够检测窗口调整大小事件,并根据窗口的大小有条件地显示输出。例如,在宽屏幕上显示完整网格,但在较小屏幕上显示卡片。

SizeChanged我已经实现了MAUI 应用程序(https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/app-lifecycle )的一个事件,可以在应用程序级别记录更改。

using Microsoft.Maui.LifecycleEvents;
    
public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
          .UseMauiApp<App>()
          .ConfigureLifecycleEvents(events =>
          {
#if WINDOWS
              events.AddWindows(windows => windows
                     .OnWindowCreated(window =>
                     {
                            window.SizeChanged += OnSizeChanged;
                     }));
#endif
          });
    
    return builder.Build();
}  

#if WINDOWS
static void OnSizeChanged(object sender, Microsoft.UI.Xaml.WindowSizeChangedEventArgs args)
{
    ILifecycleEventService service = MauiWinUIApplication.Current.Services.GetRequiredService<ILifecycleEventService>();
    service.InvokeEvents(nameof(Microsoft.UI.Xaml.Window.SizeChanged));
}
#endif
Run Code Online (Sandbox Code Playgroud)

但是我如何将其链接到单独的 MAUI 页面,以便我可以适当地检测新的窗口大小和布局?

任何建议或更好的解决方案将不胜感激

Jul*_*ian 6

在您的页面中,您可以重写 OnSizeAllocation(double width, double height) 方法:

protected override void OnSizeAllocated(double width, double height)
{
    base.OnSizeAllocated(width, height);

    //respond to size change below...
}

Run Code Online (Sandbox Code Playgroud)

请注意,每当布局更改时都会调用此函数,因此请注意不要创建无限循环或过多的渲染周期。

本文是关于 Xamarin.Forms 的,但对于 MAUI 来说,它几乎是同一件事: https: //learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/device-orientation (我无法在 MAUI 文档中找不到等效项)