Search code examples
maui

Identify the page user is on in a .NET MAUI app


How can I identify the page the user is on in a .NET MAUI shell app?

To give a little more context, here's what I'm trying to do:

My .NET MAUI app -- using Shell -- has quite a few pages, some of which are defined as tab pages in AppShell.xaml. One of the pages provides a real-time chat feature using SignalR.

I'm trying to make the experience as similar as possible to the built-in chat feature in iOS and Android where:

  • If the user is on the chat page -- in other words, actively participating in a chat -- a more subtle audio notification is played for any incoming message
  • If the user is NOT on the chat page but actively using the app, a more audible notification is played to alert the user of the incoming message
  • If the user is not using the device, then a system notification is used to alert the user

I'm using Azure Notification Hubs service to handle the third/last scenario but for me to handle the first two scenarios, I need to know what page the user is on so that I can determine what audio notification to use.

I have a ChatService that contains all the SignalR code to handle sending/receiving messages. In the MessageReceived() method, I need to determine user's page. So, this code won't be running in page code behind or a view model but in a service class which is why I need a more universal way of determining user's current "location" in my app.


Solution

  • If you are using shell try this:

    var page = Shell.Current.CurrentPage;
    

    If not try this:

    var page = Application.Current.MainPage;