Xamarin Forms modifies button text while waiting

I use Xamarin Forms to develop a cross-platform application.

I want to change the text of the "Do Something" button to something like "Wait", while the code processes the procedure and returns to "Do Something" after the code completes.

The problem is this: the button text changes only after the code completes.

A simple example:

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

    ...some code..

    btn.Text = "Do Something";
}

Is there a way to “force” the text to wait until the code completes?

+4
source share
3 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";


    }
+1
source

, async, , UI-. Yuri , async, , - , , UI-Thread, .

, . , Threads Xamarin Stud .

:

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

Button_Clicked, UI-Thread. ? , . . , , , , - (, , ..).

- , , - REST API, , . , - UI-Thread . , .

, UI- - . :

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

   ...some code...maybe async or not (take out async above if not)

   Device.BeginInvokeOnMainThread(() =>
   {
        btn.Text = "Do Something";
   });
}    

, Xamarin.Forms, . Xamarin.Forms UI-Thread . UI-Thread . , Xamarin.Android Xamarin.iOS.

. Xamarin.Forms Model-View-ViewModel (MVVM). Xamarin.Forms Bindings , OnPropertyChanged. , ViewModel, .

, , !

: Xamarin/Microsoft

+2

Xamarin.forms

  Device.BeginInvokeOnMainThread(() =>
       {
      Task.Delay(4000).Wait();
            btn.Text = "Do Something";
       });
0

Source: https://habr.com/ru/post/1660427/


All Articles