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



我正在使用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);
}

您可以使用TaskCompletionSource

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

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

而且,用法看起来像

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

为什么不利用消息传递中心来调用将删除所述项目的方法?

您可以在显示弹出窗口时订阅消息,并在单击确认按钮时接收消息。

你也可以使用现有的 xamarin 控件(即 DisplayAlert(执行相同的操作。

var input= await Application.Current.MainPage.DisplayAlert("Delete Item", "Are You sure you  want to delete this Item?", "Yes","No");
if(input)
{
myList.remove(item);
} 
else
{
return;
}

在上面的代码中,如果用户按 yes,则函数返回 true,如果 no 则返回 false。

我想补充一下阿齐里斯·莫罗拉的答案,这里是示例代码(供参考(

//Main Page Constructor
public MainPage()
{
InitializeComponent();
MessagingCenter.Subscribe<userDetail>(this, "PopUpData", (value) =>
{
string receivedData = value.username;
usernameLabel.text = receivedData;
});
}

//PopUp Page Button clicked
private async void OnClickPopUpBtn(object sender, EventArgs e)
{
await PopupNavigation.PopAsync(true);
string name = username.Text.ToString();
MessagingCenter.Send(new userDetail() { username = name }, "PopUpData");
}

//Model Class
class UserDetails
{
public string username { get; set; }
}

最新更新