Search code examples
c#xamarin.formspagination

How to transfer data from the modal form to the main? Xamarin.Forms


I need to transfer data from the modal page to the main page when I click on the button. But something does not work out.

It is necessary that there should be wait after the line until the modal window is closed:

await Navigation.PushModalAsync(modal);                         

MainPage:

string AncorName { get; set; }
Map map = new Map();

public MainPage() 
{
    AddCircle();
}

void AddCircle()
{
    map.MapClicked += async (sender, e) =>
    {
        Subscribe();
        var modal = new ModalPage();
        await Navigation.PushModalAsync(modal);

        var circle = CircleFactory.GetCircle(DataConfig.CENTER, AncorName); // AncorName = null
        map.Circles.Add(circle);

        circle.Clicked += (circleSender, ev) =>
        {
            var c = circleSender as Circle;
            DisplayAlert("Clicked on anchor", c.Tag as string, "Close");
        };
    };
}

void Subscribe() =>
    MessagingCenter.Subscribe<Page, string>(this, "AnchorsName", (sender, arg) =>
        AncorName = arg // data with modal page
    );

ModalPage:

void OnClicked(object sender, EventArgs)
{
    MessagingCenter.Send(this, "AnchorsName", ancorName.Text); // my data
    await Navigation.PopModalAsync();
}

Help me please.


Solution

  • I suggest to use MessagingCenter to send data between pages. Your modal "Send" data to your first page that "subscribe" a message.

    Here you can find some info.

    Otherwise, pass an Object to "Modal" constructor and modify it. When you close the Modal page, in the Object you should find modified data.

    You should Subscribe in OnAppearing and Unsubscribe in OnDisappearing.

    MessagingCenter.Subscribe<ModalPage, string>(this, "AnchorsName", (sender, arg) =>
        AncorName = arg // data with modal page
    );
    

    You can try to change your Send with

    MessagingCenter.Send<ModalPage, string>(this, "AnchorsName", ancorName.Text); // my data