Search code examples
c#xamarin.formsnavigationback

How to Refresh Page after navigate back. OnAppearing is not called


On my MainPage I load the current element and display data such as a card. The user can use PushAsync to navigate to the detail or edit page and update the data.

Returning from the navigation bar does not call OnAppearing, so I can not refresh the map (set location).

The way can look like this: MainPage> DetailPage> EditPage

public MainPage()
{
  InitializeComponent();

  SetLocation();
}

protected override async void OnAppearing()
{
  base.OnAppearing();

  var vm = BindingContext as MainViewModel;
  await vm?.InitializeAsync(null);

  SetLocation();
}

void SetLocation()
{
  try {
    var location = (BindingContext as MainViewModel).Location;

    if (location == null) {
      location = DataObjects.Location.Parse(AppSettings.Current.FallbackMapsLocation);
    }

    var initialPosition = new Position(
        location.Latitude,
        location.Longitude);

    var mapSpan = MapSpan.FromCenterAndRadius(
        initialPosition,
        Distance.FromMiles(1.0));

    Map.MoveToRegion(mapSpan);
  }
  catch (FeatureNotSupportedException) {
  }
}

From the EditPage I navigate back twice (DetailPage and then MainPage). My object itself is up to date and gets the changes via OnPropertyChanged, so I have the current location as well.

Should I use MessagingCenter or are there other / better options? Xamarin Forms version is 4.0 and I use shell


Solution

  • You can try to use an event if you want to trigger some commands when the navigation comes from the next page.

    Firstly, define an event in your DetailPage:

    public delegate void UpdateLocation(string info);
    public event UpdateLocation UpdateLocationEvent;
    

    Then register this event when you pushed:

    var detailPage = new DetailPage(new DetailViewModel(item));
    detailPage.UpdateLocationEvent += (info) =>
    {
    
    };
    await Navigation.PushAsync(detailPage);
    

    At last, you can call this event to trigger the code block in the MainPage. i.e. in the detail page's disappearing event:

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
    
        UpdateLocationEvent?.Invoke("location info");
    }