将Button.Background与Colors进行比较

时间:2015-06-12 17:39:17

标签: c# xaml winrt-xaml

我正在构建Windows应用商店应用。在尝试将背景与颜色进行比较时,我遇到了一个问题。


我的计划是做什么的。屏幕上有许多按钮,只需点击任何按钮,它就会将背景颜色更改为红色或绿色。从红色开始并切换每次点击的颜色。现在我想要已经点击的按钮,他们的background不应该改变。因此,后台检查if语句以跳过background颜色更改代码。

这是我的代码:

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;
        }
    }      
}

在第一个if语句中,我想检查Background是不是Red还是Green

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

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

上述代码无效。

我用什么来代替" Red"使比较工作?

2 个答案:

答案 0 :(得分:1)

我终于得到了答案。

  

谢谢@dub stylee和@Hans Passant

我将background作为solidcolorbrush关闭,然后使用其color属性并将其与Windows.Ui.Colors.Green

进行比较

这是代码。

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

答案 1 :(得分:0)

以下是Control类(Button继承自)的MSDN文档中的示例:

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";
    }
}

可以查看完整文章here

因此,要将此应用于您当前的代码,您只需将第一个if语句更改为如下所示:

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

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