.Net maui: MVVM How to catch a return from a different page using shell navigation

Viewed 725

I have set up a mainpage - detail page navigation using the Shell GoToAsync navigation

[RelayCommand] 
public async void SelectionChanged() //Friend friend
{
    if (SelectedItem == null) return;

    Friend f = SelectedItem;

    Console.WriteLine($"Selection made {f.FName} {f.LName}");

    //navigate
    var navigationParameter = new Dictionary<string, object>
    {
        { "Friend", f }
    };
    await Shell.Current.GoToAsync(nameof(DetailPage), true, navigationParameter);

    //remove selection highlight
    SelectedItem = null;
}

This works. However, I am at a loss as to how to capture the return from the detailpage in my mainpage as I need to do a refresh of my CollectionView and underlying sqlite datastore.

I have followed the Gerald Versluis video at https://www.youtube.com/watch?v=pBh5SXVSwXw for the most part.

Any ideas?

Many thanks, G

2 Answers

As it turns out this was not as hard as it might have seemed. @ToolmakerSteve pointed out a solution, but I didn't understand it at the time. The solution is to simply use the MessagingCenter approach. The documents https://docs.microsoft.com/en-us/dotnet/maui/fundamentals/messagingcenter aren't very clear on usage, but adapting the note in https://codemilltech.com/messing-with-xamarin-forms-messaging-center/ I did the following

In my detail page ViewModel and the button for returning to the main page (not the Back button which I haven't captured yet). (Using MVVM helpers version 8.0.0.0 Preview 4 (not 7, but could be adapted),

[RelayCommand]
public async void ReturnMainPage()
{
  MessagingCenter.Send(new MessagingMarker(), "IDidSomething");
}

and in the MainPageViewModel in the constructor

public MainPageViewModel()
{
  ...
  MessagingCenter.Subscribe<MessagingMarker>(this, "IDidSomething", (s) => {
    //do something in response to the detail page changing something
  });
  ...
}

Hope this helps someone in the future. G.

btw can someone tell me what the "this" is referring to? The page? What else could be put here as "this" might not be appropriate depending on the location of the code?

PS You can pass objects using this as well, see my question on .Net Maui: How to read/write (get/set) a global object from any content page (MVVM)

but I'm needing some other event to be raised when I click on some button and navigate back.

If you want to do something while navigating back, you can use BackButtonBehavior to achieve this.

And if you want some other event to be raised while clicking on some button and navigating back, you can try the following code :

 await Shell.Current.GoToAsync("..");

And backwards navigation with ".." can also be combined with a route:

 await Shell.Current.GoToAsync("../route");

For more,you can check: Backwards navigation .

Related