Jeremy P
Jeremy P

Reputation: 1407

Xamarin - Reload Page after Navigation.PopModalAsync()

I am using Xamarin to create an app for both iOS and Android, I have a use case that I press a button and it will open a Modal, then after selecting a button on the modal, it will update some information and then I need to pop the Modal off and reload the main page under it. How is that possible?

Main Page:

public partial class MainPage : ContentPage
{
    public MainPage(Object obj)
    {

        InitializeComponent();

        // do some things with obj...

        BindingContext = this;

    }

    public ButtonPressed(object sender, EventArgs args)
    {
        Navigation.PushModalAsync(new SecondaryPage(newObj));
    }

}

Secondary Page:

public partial class SecondaryPage : ContentPage
{
    public SecondaryPage(Object newObj)
    {

        InitializeComponent();

        BindingContext = this;

    }

    public ButtonPressed(object sender, EventArgs args)
    {
        // Do something to change newObj

        Navigation.PopModalAsync();
    }

}

So after the PopModalAsync(), I need to be able to call the MainPage() constructor but pass it the "newObj" that I changed in the SecondaryPage. Is this even possible?

Upvotes: 2

Views: 6072

Answers (1)

Jon G Stødle
Jon G Stødle

Reputation: 3904

The proper way to do this in .Net is to set up an event:

public partial class SecondaryPage : ContentPage
{
    public SecondaryPage(Object newObj)
    {

        InitializeComponent();

        BindingContext = this;

    }

    // Add an event to notify when things are updated
    public event EventHandler<EventArgs> OperationCompeleted;

    public ButtonPressed(object sender, EventArgs args)
    {
        // Do something to change newObj
        OperationCompleted?.Invoke(this, EventArgs.Empty);
        Navigation.PopModalAsync();
    }

}

public partial class MainPage : ContentPage
{
    public MainPage(Object obj)
    {

        InitializeComponent();

        // do some things with obj...

        BindingContext = this;

    }

    public ButtonPressed(object sender, EventArgs args)
    {
        var secondaryPage = new SecondaryPage(newObj);
        // Subscribe to the event when things are updated
        secondaryPage.OperationCompeleted += SecondaryPage_OperationCompleted;
        Navigation.PushModalAsync(secondaryPage);
    }

    private void SecondaryPage_OperationCompleted(object sender, EventArgs e)
    {
        // Unsubscribe to the event to prevent memory leak
        (sender as SecondaryPage).OperationCompeleted -= SecondaryPage_OperationCompleted;
        // Do something after change
    }
}

Upvotes: 2

Related Questions