Search code examples
c#xamlmaui

How to access PreviousPage property in NavigatedToEventArgs in MAUI


I am trying to determine which was the previous page for current page in .NET MAUI application.

For example, there are 3 pages Page1, Page2, Page3

When going from Page1 to Page2, in Page2, I would like to access PreviousPage property which gives me "Page1" as value.

When going from Page3 to Page2, in Page2, PreviousPage property gives me "Page3" as value.

^^ However, I can only see "PreviousPage" property member in Debug mode when VS hits breakpoint. I cannot access it in code. Intellisense does not show this too.

How can I access and use this "PreviousPage" in my code? Is there any other way?

See screenshot.

enter image description here

I am using: Microsoft Visual Studio Community 2022 (64-bit) - Preview Version 17.5.0 Preview 1.0

Thank you.


Solution

  • Like @h-a-h mentioned, custom logic was the way. I implemented sort of workaround to make it work. I used navigation parameters.

    My viewmodel constructor has attribute like this:

    [QueryProperty("IsBack", "IsBack")]
    public class Page2ViewModel
    {
     //called from code-behind on OnNavigatedTo event using associated Command.Execute
     async Task LoadData()
     {
      if(IsBack == false) 
      {
       await _repos.GetListAsync();
      }
     }
    
     public bool IsBack {get;set;}
    }
    

    When going from Page1 to Page2, I do:

    await Shell.Current.GoToAsync($"{nameof(View.Page2)}?IsBack={false}");
    

    When going back to Page2 from Page3, I do:

    await Shell.Current.GoToAsync($"..?IsBack={true}");
    

    At least this way I know "when" Page2 is visited so as to prevent loading of data again. Though this does not let me know if I am coming back to Page2 from Page3 or Page'n', it solves my current requirement.

    One can always use query parameters to provide the parent page. e.g., from Page5 to Page2, we can do:

    await Shell.Current.GoToAsync($"..?IsBack={true}&ParentPageId={nameof(View.Page5)}");
    

    provided Page2's ViewModel has this QueryParameter attribute.

    [QueryProperty("ParentPageId", "ParentPageId")]
    

    Not very elegant but workable.

    Thank you all for your help.