我正在撰寫一個小型 Xamarin.Forms 應用程式,并嘗試執行一些操作,例如顯示警報或顯示活動指示器。但是,我在代碼中撰寫的所有內容都只在方法結束時執行,即使是 Activity Indicator,這當然不是目標。不同的警報甚至顯示在 LIFO 中,因此代碼中的最后一個首先出現。
這是 xaml.cs 中的代碼:
private void btConnexion_Clicked(object sender, EventArgs e)
{
ai.IsRunning = true;
IsBusy = true;
LoginViewModel vm = (LoginViewModel)this.BindingContext;
DisplayAlert(AppResources.Sorry, "Beginning", "Ok");
try
{
DisplayAlert(AppResources.Sorry, "In the try", "Ok");
if (vm.Valide())
{
Task t = Task.Run(async () => { await vm.AuthentificationAPI(); });
if (!t.Wait(TimeSpan.FromSeconds(5)))
{
DisplayAlert(AppResources.Sorry, AppResources.TryAgainLater, "Ok");
}
if (t.IsCompleted)
{
GetAllData();
Application.Current.MainPage = new AppShell();
Shell.Current.GoToAsync("//main");
}
}
else
DisplayAlert(AppResources.Error, AppResources.MissingFieldsErrorMessage, "Ok");
}
catch (Exception ex)
{
DisplayAlert(AppResources.Sorry, AppResources.TryAgainLater " (" ex.Message ")", "Ok");
}
finally
{
ai.IsRunning = false;
DisplayAlert(AppResources.Sorry, "Finally", "Ok");
}
DisplayAlert(AppResources.Sorry, "After finally", "Ok");
}
我在 .xaml 中呼叫它的地方:
<Button Text="{x:Static resource:AppResources.Login}"
x:Name="btConnexion"
BackgroundColor="#AADC14"
Padding="0,0,0,0"
Clicked="btConnexion_Clicked"/>
我在方法中放置了一些警報,顯示“在嘗試中”、“開始”等。如果我逐步除錯代碼,則所有警報僅在方法結束時執行一次,而不是在執行期間匯編。在 FILO 中,第一個是“最終之后”,然后是“最終”,等等。活動指示器甚至沒有顯示,因為我想的原因相同。
我不知道它是否有任何改變,但必須按照 xaml.cs 中撰寫的方式編譯 xaml:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
uj5u.com熱心網友回復:
將 await 放在顯示警報之前,如下所示
await DisplayAlert ("Alert", "You have been alerted", "OK");
uj5u.com熱心網友回復:
我創建了一個小實體來更改DisplayAlert和ActivityIndi??cator方法的內部狀態。
這是cs代碼:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
//For DisplayAlert you only need to add await before the method.
private async void btConnexion_Clicked(object sender, EventArgs e)
{
if ((sender as Button).Text == "test")
{
await DisplayAlert("sorry", "try again later", "Ok");
}
await DisplayAlert("end", "end", "Ok");
}
//For ActivityIndicator, I use Task.Delay to make the effect clearer
private async void Button_Clicked(object sender, EventArgs e)
{
ActivityIndicator indicator = new ActivityIndicator();
indicator.IsRunning = true;
indicator.IsVisible = true;
indicator.Color = Color.Black;
stacklayout.Children.Add(indicator);
await Task.Delay(3000);
indicator.IsRunning = false;
indicator.IsVisible = false;
}
}
這是xaml代碼:
<StackLayout x:Name="stacklayout">
<Button Text="test"
x:Name="btConnexion"
BackgroundColor="#AADC14"
Padding="0,0,0,0"
Clicked="btConnexion_Clicked"/>
<Button Text="ActivityIndicator" Clicked="Button_Clicked"></Button>
</StackLayout>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/326192.html
上一篇:有什么辦法可以在不畫畫的情況下確定跨源影像是否會玷污畫布?
下一篇:如何在Autofac中的scope.Resolve<Service<T>>().Method1()中使用運行時型別引數?
