Leonardo Lima Almeida Leonardo Lima Almeida - 1 year ago 118
C# Question

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?

Answer Source
    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";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download