Check if the ContentPage is a MainPage

Jassim Al Rahma 1,526 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

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,917 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,298 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 36,061 Reputation points Microsoft Vendor
    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