Change maui button background color at runtime

Haviv Elbsz 2,071 Reputation points
2022-08-29T08:05:28.88+00:00

Hi All

I have a lengthy method in my application

when the application start I want to change
the run button background color to red background color
and when the lengthy method finished
I change it to it's original background color.

but that's only works if I change the textcolor
but when I change the background color
that have no effect.

thank you for any help

Developer technologies .NET .NET MAUI
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. dg2k 1,416 Reputation points
    2022-09-06T10:21:05.003+00:00

    @Haviv Elbsz - Put a line of code:

    await Task.Delay(timeout);

    after:

    RunButton.BackgroundColor = Colors.Green;

    Use a suitable value for timeout, say start from 100 to about 500. This gives the update time for UI.
    I think your busy loop may not allow the UI to update the Button color setting and awaited Task.Delay() may do the trick to give the UI to update itself.

    UPDATE:
    The difference between Background and BackgroundColor is:

    • Background is a Brush
    • BackgroundColor is a Color

    There is a subtle difference between a Brush and Color (Color is a property of Brush but not another way round).

    But on Maui (and Xamarin) you can use either Background or BackgroundColor on elements like Buttons and layouts and the necessary conversion is done for us internally.

    Sometimes Button color setting could appear problematic if there are App-wide style definitions (possibly automatically generated on App creation) do overriding. Worth checking if this applies to your App.

    1 person found this answer helpful.
    0 comments No comments

  2. Haviv Elbsz 2,071 Reputation points
    2022-09-16T08:59:44.263+00:00

    I got it by using background instead
    of backgroundcolor

    I don't know why this works
    I'll appreciate it if someone can explain

    thank you


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.