【问题标题】:DisplayAlert methods only executed at the end of the method in XamarinDisplayAlert 方法仅在 Xamarin 中的方法结束时执行
【发布时间】:2021-12-06 05:10:48
【问题描述】:

我正在编写一个小型 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"/>

我在methodd中放了一些alerts,显示“In the try”、“Beginning”等。如果我一步步调试代码,所有的alerts只会在方法结束时执行一次,而是在编译期间。而在 FILO 中,第一个是“After finally”,然后是“Finally”等。而且活动指示器甚至没有显示,原因与我想的相同。

我不知道它是否会改变任何东西,但是 xaml 必须按照 xaml.cs 中的编写方式进行编译:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage

【问题讨论】:

  • 在 DisplayAlert 之前放置等待

标签: c# xaml xamarin compilation activity-indicator


【解决方案1】:

我创建了一个小实例来更改 DisplayAlertActivityIndi​​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>

【讨论】:

  • 嗨,它确实对我有用。但要感谢Task.Delay。如果我使用您的代码,如果没有这种延迟,它将无法正常工作。还是我应该更改代码中的某些内容?
  • 这只是延迟。不加的话,代码运行瞬间结束,看不到是否生效。
  • 我的意思是在我的代码中我必须使用一个需要几秒钟的 API,但即使这样,AI 也没有显示(等待 vm.AuthentificationAPI();)
  • 我认为您在 API 请求中使用了 await。它不会让线程等待,而是启动一个新线程。
  • 问题解决了吗?
【解决方案2】:

如下所示在显示警报之前放置等待

await DisplayAlert ("Alert", "You have been alerted", "OK");

【讨论】:

  • 非常感谢!它适用于 DisplayAlert,但不适用于 Activity Indicator。这仅在过程结束时打开。有什么建议吗?
【解决方案3】:

最后通过将 Activity Indicator 放在 GridView 的末尾而不是开头来解决问题,如下所示。所以 AI 在那里,但不可见,因为被 AbsoluteLayout 隐藏在背景中。

</AbsoluteLayout>

<ActivityIndicator 
    IsRunning="{Binding IsBusy}"
    IsVisible="{Binding IsBusy}"
    Color="Red"
    VerticalOptions="CenterAndExpand" 
    HorizontalOptions="CenterAndExpand" 
    />

【讨论】:

    猜你喜欢
    • 2011-03-11
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2011-01-08
    • 2017-02-21
    相关资源
    最近更新 更多