EsAMe
EsAMe

Reputation: 305

Programmatically set foreground text color of button

This is for a UWP app. ReturnCharacter() will either return o or x. If x was returned, a blue color is set. Else (o was returned) and a red color is set. Then, an x or o is written on the button using the previously set color. So, we should end up with either a blue x or a red o on the button. Tried the following but it isn't working. I just get a brown x or o. Wonder where that color even came from. Also, is there a way to use hex values for colors instead of RGB values?

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        char c = ReturnCharacter();

        if (c == 'x')
        {
            button1.Foreground = new SolidColorBrush(Color.FromArgb(51, 178, 255, 0));
        }
        else
        {
            button1.Foreground = new SolidColorBrush(Color.FromArgb(255, 104, 51, 0));
        }

        button1.Content = c;
    }

Upvotes: 0

Views: 550

Answers (2)

Charlie
Charlie

Reputation: 9108

Color.FromArgb() takes 4 parameters. The first one is the alpha channel. If you want the color to be fully opaque, 255 is the correct value.

You probably want:

private void Button1_Click(object sender, RoutedEventArgs e)
{
    char c = ReturnCharacter();

    if (c == 'x')
    {
        button1.Foreground = new SolidColorBrush(Color.FromArgb(255, 51, 178, 255));
    }
    else
    {
        button1.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 104, 51));
    }

    button1.Content = c;
}

or more simply and efficiently:

SolidColorBrush blue = new SolidColorBrush(Color.FromArgb(255, 51, 178, 255));
SolidColorBrush red = new SolidColorBrush(Color.FromArgb(255, 255, 104, 51))

private void Button1_Click(object sender, RoutedEventArgs e)
{
    char c = ReturnCharacter();
    button1.Foreground = c == 'x' ? blue : red;
    button1.Content = c;
}

Upvotes: 1

aybe
aybe

Reputation: 16652

Color.FromArgb expects A, R, G, B components, in that order

No wonder why you're getting the following colors:

enter image description here

enter image description here

You want this instead:

enter image description here

enter image description here

Color.FromArgb(255, 51, 178, 255);
Color.FromArgb(255, 255, 104, 51);

Upvotes: 1

Related Questions