Check if the ContentPage is a MainPage

Jassim Al Rahma 1,616 Reputation points
2023-03-29T17:47:07.24+00:00

Hi,

In .NET MAUI, how can I check the current page is a Mainpage?

Thanks,

Jassim

Developer technologies | .NET | .NET MAUI
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2023-03-30T03:04:59.62+00:00

    Hello,

    You could set a Title on your page and use it to determine if the current page is MainPage:

    // in xaml
    <ContentPage ...
                 x:Class="MauiApp14.NewPage1"
                 Title="NewPage1">
    // in c#
    var name = AppShell.Current.CurrentPage.Title;
    if (name.Equals("MainPage"))
    {
    	Console.WriteLine("MainPage");
    }else
    {
    	Console.WriteLine(name);
    }
    

    Update:

    This problem occurs because you put var name = AppShell.Current.CurrentPage.ClassId; is placed in the page's constructor, and the CurrentPage has not yet been assigned, so this error is caused.

    For any way to get page properties, a more recommended way is to put them in the page's OnAppearing method.

    protected override void OnAppearing()
        {
            base.OnAppearing();
            var name = AppShell.Current.CurrentPage.ClassId;
            if ...
        }
    

    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.


0 additional answers

Sort by: Most helpful

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.