Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms change text of button while wait

I'm using Xamarin Forms to develop a Cross-Platform app.

I want to change the Text of the button "Do Something" to something like "Wait", while the code is processing the routine, and back to "Do Something" after the code finish to run.

The problem is: The button text only change after the code is completed.

Simple Exemple:

private void Button_Clicked(object sender, EventArgs e)
{
    var btn = (Button)sender;
    btn.Text = "Wait";

    ...some code..

    btn.Text = "Do Something";
}

There's some way to "force" the update of Text to "Wait" before the code finish?

like image 965
Leonardo Lima Almeida Avatar asked Nov 10 '16 17:11

Leonardo Lima Almeida


1 Answers

    private async void Btn1_Clicked(object sender, EventArgs e)
    {
       btn1.Text = "Wait";

        await Task.Run(async () =>
        {
            for (int i = 1; i <= 5; i++)
            {
                //if your code requires UI then wrap it in BeginInvokeOnMainThread
                //otherwise just run your code
                Device.BeginInvokeOnMainThread(() =>
                {
                    btn1.Text = $"Wait {i}";
                });
                await Task.Delay(1000);
            }
        });

        btn1.Text = "Done";


    }
like image 54
Yuri S Avatar answered Oct 03 '22 15:10

Yuri S