我正在构建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"使比较工作?
答案 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)