Typically, one pops the current page using this from the NavigationStack:
Navigation.PopAsync( true );
How to I use Naviga
As @SushiHangover mentioned, MessagingCenter
is a good option.
Another way would be to subscribe to Page2's OnDisappearing()
event from page1 and do something to the Page1 UI/data like so:
Edit: The old way I answered this question (see changelog) does work but I have since modified how I do it, after seeing others' examples, to prevent memory leaks. It is better to unsubscribe from the Disappearing
event after it has been used. If you plan to use it again then you can just resubscribe to it before running PushAsync()
again on your Page2
instance:
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
}
Here is what I had to do to get hvaughan3's solution to work for me:
private async void OnGoToPage2Clicked(object sender, EventArgs args) {
Page2 page2 = new Page2();
page2.Disappearing += Page2_Disappearing;
await Navigation.PushAsync(page2);
}
private void Page2_Disappearing(object sender, EventArgs e) {
this.Refresh(); // what your refresh or init function is.
}
When I saw that solution I liked that as the option for me since I'm real heavy into using events to solve most of my problems. Thanks hvaughan3!
I'm assuming that the data model that you are using is not observable/bindable and thus the page is not "auto-updated"...
You could use MessagingCenter
to publish a "Refresh Event" to avoid coupling the two Page
s with events...
In your MainPage:
MessagingCenter.Subscribe<MainPage> (this, "RefreshMainPage", (sender) => {
// Call your main page refresh method
});
In your Second Page:
MessagingCenter.Send<MainPage> (this, "RefreshMainPage");
Navigation.PopAsync( true );
https://developer.xamarin.com/guides/xamarin-forms/messaging-center/