Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I await modal form dismissal using Xamarin.Forms?

Using Xamarin.Forms how can I use make an async method that waits for the form to dismiss? If I use

await Navigation.PushModalAsync(page);

it will return once the animation is finished not when the page is dismissed.

I want a to create modal Task SignInAsync method that return true if sign-in is successful.

like image 883
Jamey McElveen Avatar asked Jun 11 '14 23:06

Jamey McElveen


Video Answer


1 Answers

You can do this by triggering an event in your login page and listen for that event before going on, but you want the full TAP support and I second you there. Here's a simple yet working 2 page app that does just this. You'll obviously want to use ContentPage custom subclass and have proper methods instead of my quick Commands, but you get the idea, and it saves me typing.

public static Page GetFormsApp ()
{
    NavigationPage navpage = null;
    return navpage = new NavigationPage (new ContentPage { 
        Content = new Button {
            Text = "Show Login dialog",
            Command = new Command (async o => {
                Debug.WriteLine ("Showing sign in dialog");
                var result = await SignInAsync (navpage);
                Debug.WriteLine (result);
            })
        }
    });
}

static Task<bool> SignInAsync (NavigationPage navpage)
{
    Random rnd = new Random ();
    var tcs = new TaskCompletionSource<bool> ();
    navpage.Navigation.PushModalAsync (new ContentPage {
        Content = new Button {
            Text = "Try login",
            Command = new Command ( o => {
                var result = rnd.Next (2) == 1;
                navpage.Navigation.PopModalAsync ();
                tcs.SetResult (result);
            })
        }
    });
    return tcs.Task;
}

The minor drawback is that the Task<bool> returns before the end of the pop modal animation, but that's:

  1. easy to fix
  2. only an issue if you're awaiting that result to push a new modal Page. Otherwise, meh, just go on.
like image 55
Stephane Delcroix Avatar answered Sep 30 '22 19:09

Stephane Delcroix