如何使用 Xamarin.Forms 等待模态表单关闭? [英] How can I await modal form dismissal using Xamarin.Forms?

查看:36
本文介绍了如何使用 Xamarin.Forms 等待模态表单关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Xamarin.Forms 我如何使用 make 一个等待表单关闭的异步方法?如果我使用

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.

我想要一个创建模态任务 SignInAsync 方法,如果登录成功则返回 true.

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

推荐答案

您可以通过在登录页面中触发一个事件并在继续之前侦听该事件来实现此目的,但您需要完整的 TAP 支持,我在那里为您提供支持.这是一个简单但有效的 2 页应用程序,可以做到这一点.您显然希望使用 ContentPage 自定义子类并拥有适当的方法而不是我快速的 Command,但是您明白了,它可以节省我的输入时间.

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;
}

一个小缺点是 Task 在弹出模态动画结束之前返回,但是:

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

  1. 易于修复
  2. 仅当您等待该结果推送新的模态 Page 时才会出现问题.否则,嗯,继续.
  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.

这篇关于如何使用 Xamarin.Forms 等待模态表单关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆