Search code examples
c#xamarinstacklayout

Xamarin set BackgroundColor of StackLayout on tapped


StackLayout sl1 = this.FindByName<StackLayout>("myStackLayout");
sl1.GestureRecognizers.Add(
    new TapGestureRecognizer() {
        Command = new Command(() => { 

              Task.Run(() => { 

                 // When this line hits, background is set...  
                 sl1.BackgroundColor = Color.FromHex("CCCCCC");



                 //this.Refresh(); << force Refresh UI function or something????

                 Task.Delay(400);

                 // When this line hits, background is reset...  
                 sl1.BackgroundColor = Color.FromHex("EEEEEE");

              });


        }) 
   });

The above code is working as expected when i debug this code line by line.

However, when i run this code without debugging, the UI will not update the BackgroundColor.

Then when i try to debug to see what is happening, it seems to work.

  • Why is this not working without debugging?
  • Is there a function that forces the UI to update?
  • Any other ideas to get the same effect?

EDIT:

The first time it also works.

EDIT 2 (Solution):

Using a combination of the two answers i got it to work using the following code:

        StackLayout sl1 = this.FindByName<StackLayout>("myStackLayout");
        sl1.GestureRecognizers.Add(
        new TapGestureRecognizer()
        {
            Command = new Command(async () =>
            {
                sl1.BackgroundColor = Color.FromHex("#CCCCCC");

                await Task.Run(async () => { 
                    await Task.Delay(100);
                    Device.BeginInvokeOnMainThread(() => { 
                        sl1.BackgroundColor = Color.FromHex("#EEEEEE");
                    });
                });

            })
        });

Solution

  • You are trying to update the UI from a background thread and all UI changes should be done on the main thread.

    Device.BeginInvokeOnMainThread(() =>
    {
        sl1.BackgroundColor = Color.FromHex("CCCCCC");
    });