Xamarin 创建 Alert
首先创建一个文件:
AlertCallbacksPage.xaml:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="one.AlertCallbacksPage">
<StackLayout>
<Button Text="Invoke Alert" FontSize="Large" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" Clicked="OnButtonClicked"/>
<Label x:Name="label" Text="Tap Button to invoke alert" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage>
AlertCallbacksPage.xaml.cs:
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace one
{
public partial class AlertCallbacksPage : ContentPage
{
bool result;
public AlertCallbacksPage()
{
InitializeComponent();
}
void OnButtonClicked(object sender, EventArgs args) {
Task<bool> task = DisplayAlert("Simple Alert", "Decide on an option", "yes or ok", "no or cancel");
task.ContinueWith(AlertDismissedCallback);
label.Text = "Alert is currently displayed";
}
void AlertDismissedCallback(Task<bool> task) {
result = task.Result;
Device.BeginInvokeOnMainThread(DisplayResultCallback);
}
void DisplayResultCallback() {
label.Text = String.Format("Alert {0} button was pressed", result ? "OK" : "Cancel");
}
}
}
运行效果:
点击 Invoke Alert 按钮:
选择"no or cancel":
选择"yes or ok":