【问题标题】:How to Refresh Page after navigate back. OnAppearing is not called导航返回后如何刷新页面。不调用 OnAppearing
【发布时间】:2019-06-11 17:07:45
【问题描述】:

在我的 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

【问题讨论】:

  • 您确实没有包含足够的代码来说明您如何传递数据。如果您使用数据绑定和 INPC,那么通常 UI 应在数据更改时自行更新。
  • 可以使用详情页的onDisappearing()方法。并重新加载数据。使您的设置位置方法静态并从详细信息 onDisappearing() 调用它
  • @Jason:我使用数据绑定,但地图没有当前位置的属性
  • 啊,好吧——那我可能会使用 MessagingCenter 来做
  • 好的,谢谢你,杰森!

标签: c# xamarin.forms navigation back


【解决方案1】:

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

首先,在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);

最后,您可以调用此事件来触发 MainPage 中的代码块。即在详情页的消失事件中:

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

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

【讨论】:

  • 感谢您的提示,我现在结合使用 MessagingCenter 和 Delegates
  • @jckruse 很高兴你解决了它。如果您觉得这有帮助,请接受此作为答案。
猜你喜欢
  • 2012-08-12
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 2014-12-02
相关资源
最近更新 更多