如何刷新导航上的一个但最后一个ContentPage

Ste*_*eAp 4 c# xamarin xamarin.forms

通常,使用NavigationStack中的一个弹出当前页面:

   Navigation.PopAsync( true );
Run Code Online (Sandbox Code Playgroud)

如何使用Navigation在当前页面之前重绘页面?

背景:当前页面改变了需要在一页但最后一页重新呈现的内容.

Sus*_*ver 9

我假设您使用的数据模型不可观察/可绑定,因此页面不是"自动更新"...

您可以使用MessagingCenter发布"刷新事件"来避免将两个Pages与事件耦合...

在您的MainPage中:

MessagingCenter.Subscribe<MainPage> (this, "RefreshMainPage", (sender) => {
    // Call your main page refresh method
});
Run Code Online (Sandbox Code Playgroud)

在你的第二页:

   MessagingCenter.Send<MainPage> (this, "RefreshMainPage");
   Navigation.PopAsync( true );
Run Code Online (Sandbox Code Playgroud)

https://developer.xamarin.com/guides/xamarin-forms/messaging-center/


hva*_*an3 6

正如@SushiHangover 提到的,MessagingCenter是一个不错的选择。

另一种方法是OnDisappearing()从 page1订阅 Page2 的事件并对 Page1 UI/data 做一些事情,如下所示:

编辑:我回答这个问题的旧方法(请参阅更改日志)确实有效,但在看到其他人的示例后,我修改了我的做法,以防止内存泄漏。Disappearing事件使用后最好取消订阅。如果您打算再次使用它,那么您可以在PushAsync()再次在您的Page2实例上运行之前重新订阅它:

private async void OnGoToPage2Clicked(object sender, EventArgs args) {
    Page2 page2 = new Page2();

    page2.Disappearing += OnPage2Disappearing;

    await Navigation.PushAsync(page2);
}

private async void OnPage2Disappearing(object sender, EventArgs eventArgs) {
    await _viewModel.RefreshPage1Data(); //Or how ever you need to refresh the data
    ((Page2)sender).Disappearing -= OnPage2Disappearing; //Unsubscribe from the event to allow the GC to collect the page and prevent memory leaks
}
Run Code Online (Sandbox Code Playgroud)