aca
aca

Reputation: 1121

Is there a way to come back on last page in Navigation stack, and not execute OnApearing method in Xamarin?

So, I have Page1, with some input fields that my user already filled, and, there is a button that opens a new Page (let's call it Page2).

This is the code I used to go on Page2.

Application.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(new Page2()));

This is the code I used to came back on Page1.

private async void GoBackButton_Clicked(object sender, EventArgs e)
    {
        await Application.Current.MainPage.Navigation.PopModalAsync();
    }

Now, I'd like to, somehow, when user finishes what he had on Page2, he presses the button, called GoBack, then he comes back on the Page1, and the OnApearing method of Page1's ViewModel is NOT getting executed. Is this doable?

Not sure if important, but I'm using VS22, on Windows10.

Upvotes: 1

Views: 675

Answers (1)

Michal Diviš
Michal Diviš

Reputation: 2206

This is what I'm using in some of my apps. The logic is: Page1 loads data on the first load and then only reloads data when reload requested.

Here's an example:

Page1.xaml.cs

public partial class Page1 : ContentPage
{
    private bool _isFirstLoad = true;
    private bool _isReloadRequested;

    public Page1()
    {
        InitializeComponent();
    }

    private async Task OpenPage2Async()
    {
        //navigate to Page2
        await Application.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(new Page2(() => _isReloadRequested = true)));
    }

    protected override void OnAppearing()
    {
        if (_isFirstLoad)
        {
            _isFirstLoad = false;
            ReloadData();
            return;
        }

        if (_isReloadRequested)
        {
            ReloadData();
            _isReloadRequested = false;
        }
    }

    private void ReloadData()
    {
        //reload data...
    }
}

Page2.xaml.cs

public partial class Page2 : ContentPage
{
    private readonly Action _requestReload;

    public Page2(Action requestReload)
    {
        InitializeComponent();
        _requestReload = requestReload;
    }

    private async Task GoBackAsync()
    {
        //invoke callback to set Page1's _isReloadRequested to true
        _requestReload?.Invoke();
        //go back to Page1
        await Application.Current.MainPage.Navigation.PopModalAsync();
    }
}

Upvotes: 2

Related Questions