Comparing Button.Background with Colors

1.6k Views Asked by At

I am building a Windows Store application. I am facing a problem when trying to compare the background with a color.


What My Program Does. There are many buttons on the screen and on a click of any button it changes the background color of it to either red or green. Starting from Red and switching color per click.Now I want that the buttons that already have been clicked, their background should not change. Thus the background checking if statement to skip the background color change code.

This is my code:

private void changecolor(object sender, RoutedEventArgs e)
{   
    if ((sender as Button).Background != "Red" && (sender as Button).Background != "Green")
    {
        if (counter == 1)
        {
            (sender as Button).Background = new SolidColorBrush(Windows.UI.Colors.Green);
            (sender as Button).Content = "Green";

            counter = 0;
        }
        else if (counter == 0)
        {  
            (sender as Button).Background = new SolidColorBrush(Windows.UI.Colors.Red);
            (sender as Button).Content = "Red";

            counter = 1;
        }
    }      
}

On the first if statement, I want to check if the Background is not Red or Green.

(sender as Button).Background != Windows.UI.Colors.Red

(sender as Button).Background != "Red"

The above code doesn't work.


What Do I write in Place of "Red" to make the comparison work?

2

There are 2 best solutions below

0
On BEST ANSWER

I finally have gotten the answer to this.

Thank you @dub stylee and @Hans Passant

I caste the background as a solidcolorbrush then used its color property and compared it to the Windows.Ui.Colors.Green

Here is the code.

if (((sender as Button).Background as SolidColorBrush).Color != Windows.UI.Colors.Green && ((sender as Button).Background as SolidColorBrush).Color != Windows.UI.Colors.Red)
7
On

Here is an example from the MSDN documentation for the Control class (which Button inherits from):

void ChangeBackground(object sender, RoutedEventArgs e)
{
    if (btn.Background == Brushes.Red)
    {
        btn.Background = new LinearGradientBrush(Colors.LightBlue, Colors.SlateBlue, 90);
        btn.Content = "Control background changes from red to a blue gradient.";
    }
    else
    {
        btn.Background = Brushes.Red;
        btn.Content = "Background";
    }
}

The full article can be viewed here.

So to apply this to your current code, you can simply change your first if statement to look like this:

var redBrush = new SolidColorBrush(Colors.Red);
var greenBrush = new SolidColorBrush(Colors.Green);

if ((sender as Button).Background == redBrush ||
    (sender as Button).Background == greenBrush)