Issue with Application.Current.MainPage.Width Returning -1 in .NET MAUI

KarPreet 60 Reputation points
2024-11-26T05:30:23.8133333+00:00

I am migrating my project from Xamarin to .NET MAUI. In Xamarin, I use Application.Current.MainPage.Width to get the width of the main page, and it works as expected.

However, in .NET MAUI, when I try to access Application.Current.MainPage.Width, it always returns -1. It seems like the layout hasn't been fully loaded when I try to access it.

I have explored using DeviceDisplay.MainDisplayInfo as a workaround to get the screen dimensions, but I specifically need to use Application.Current.MainPage.Width since my use case involves layout calculations that depend on the actual page dimensions.

Is there a specific lifecycle or event in .NET MAUI where I should access the width property to ensure it has been initialized? Why does this behavior differ from Xamarin?

Any guidance or best practices would be greatly appreciated!

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,696 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 45,181 Reputation points Microsoft Vendor
    2024-11-27T02:02:21.76+00:00

    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.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.