如何暂停方法直到从 Xamarin.Forms 中的 Rg.Plugins.Popup 获得响应?

Moh*_*nad 2 popup xamarin.forms

在从列表中删除项目之前,我使用 Rg.Plugins.Popup 进行简单的确认弹出窗口,例如“您确定要从列表中删除 Item1?”。我需要知道如何暂停删除方法,直到它从弹出窗口中获得确认。

private async void MenuItem_Clicked_1(object sender, EventArgs e)
        {

            var menuItem = sender as MenuItem;
            var item= menuItem.CommandParameter as Item;


            var page = new popupAlert(item);
            await Navigation.PushPopupAsync(page);

           // Pause here
             myList.remove(item);
        }
Run Code Online (Sandbox Code Playgroud)

Sha*_*raj 8

您可以使用TaskCompletionSource

例如,PopupAlert使用异步Show方法创建页面:

public class PopupAlert : PopupPage
{
    TaskCompletionSource<bool> _tcs = null;
    public PopupAlert()
    {
        var yesBtn = new Button { Text = "OK" };
        var noBtn = new Button { Text = "Cancel" };

        yesBtn.Clicked += async (sender, e) =>
        {
            await Navigation.PopAllPopupAsync();
            _tcs?.SetResult(true);
        };
        noBtn.Clicked += async (sender, e) =>
        {
            await Navigation.PopAllPopupAsync();
            _tcs?.SetResult(false);
        };

        Content = new StackLayout
        {
            BackgroundColor = Color.White,
            VerticalOptions = LayoutOptions.Center,
            Padding = 20,
            Children = {
                new Label { Text = "Are you sure you want to delete?" },
                new StackLayout {
                    Orientation = StackOrientation.Horizontal,
                    Children = { yesBtn, noBtn }
                }
            }
        };
    }

    public async Task<bool> Show()
    {
        _tcs = new TaskCompletionSource<bool>();
        await Navigation.PushPopupAsync(this);

        return await _tcs.Task;
    }
}
Run Code Online (Sandbox Code Playgroud)

而且,用法看起来像

private async void MenuItem_Clicked_1(object sender, EventArgs e)
{
    var menuItem = sender as MenuItem;
    var item = menuItem.CommandParameter as Item;

    var popupAlert = new PopupAlert();
    var result = await popup.Show(); //wait till user taps/selects option 

    if(result) //check for user selection here
        myList.remove(item);
}
Run Code Online (Sandbox Code Playgroud)