Reputation: 135
I am experimenting with MAUI for a windows app that needs to work on a multitude of screen sizes from wide screen to tablet and allow window resizing.
I need to be able to detect a windows resize event and conditionally display output dependent on the size of the window. e.g., full grid on wide screens but cards on smaller ones.
There is a SizeChanged
event for the MAUI app (https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/app-lifecycle) which I have implemented and can log the changes at the app level.
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
But how do I link this to an individual MAUI page so that I can detect the new window size and layout as appropriate?
Any advice or a better solution would be appreciated
Upvotes: 4
Views: 6163
Reputation: 2020
Actually im using this package, very useful for what you need, you can set different screen sizes and then you use it with a reference. I use it now and set the sizes from small phone, to a big tablet (used as a payment totem)
Code Sample:
<Border
WidthRequest="{markups:OnScreenSize Default='160', Medium='170', Large='200', ExtraLarge='220'}"
HeightRequest="{markups:OnScreenSize Default='100', Medium='110', Large='130', ExtraLarge='160'}" />
In this case, when app is running it will check the markup with the screen size set as default / medium / large / etc. and whenever the case is, it will change or not on the parameters you set to the markup
Upvotes: 0
Reputation: 8866
In your page, you can override the OnSizeAllocated(double width, double height) method:
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
//respond to size change below...
}
Note that this gets called whenever the layout changes, so be careful to not create an infinite loop or excessive rendering cycles.
This article is about Xamarin.Forms but for MAUI it's very much the same thing: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/device-orientation (I couldn't find the equivalent in the MAUI documentation)
Upvotes: 8