Hello,
However, in .NET MAUI, when I try to access Application.Current.MainPage.Width, it always returns -1
Maui has optimized the initialization order of controls. Now if you want to get the width of the Page, you need to wait until OnSizeAllocated
is executed to get the correct width.
Please refer to the following code:
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
var w = Application.Current.MainPage.Width;
Console.WriteLine(w);
}
Updated:
For Shell-based applications, you need to obtain the page width through the Shell API.
var w = AppShell.Current.Window.Width;
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.