返回后如何刷新页面。不调用 OnAppearing

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

在我的 MainPage 上,我加载了当前元素并显示了卡片等数据。 用户可以使用 PushAsync 导航到详细信息或编辑页面并更新数据。

导航栏返回没有调用OnAppearing,所以无法刷新地图(设置位置)

方法可以是这样的: 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) {
  }
}

我从 EditPage 向后导航了两次(DetailPage,然后是 MainPage)。 我的对象本身是最新的并通过 OnPropertyChanged 获取更改,所以我也有当前位置。

我应该使用 MessagingCenter 还是有其他/更好的选择? Xamarin Forms 版本是 4.0,我使用 shell

如果你想在下一页导航过来时触发一些命令,可以尝试使用事件

首先,在您的 DetailPage:

中定义一个事件
public delegate void UpdateLocation(string info);
public event UpdateLocation UpdateLocationEvent;

然后在你推送的时候注册这个事件:

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

};
await Navigation.PushAsync(detailPage);

最后就可以调用这个事件来触发主页面的代码块了。即在详情页面的消失事件中:

protected override void OnDisappearing()
{
    base.OnDisappearing();

    UpdateLocationEvent?.Invoke("location info");
}