【发布时间】:2015-06-12 17:39:16
【问题描述】:
我正在构建一个 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"
上面的代码不起作用。
我应该写什么来代替“红色”来进行比较?
【问题讨论】:
-
也许您看到的错误代码可能会有所帮助。可以看到,将
Background属性值设置为SolidColorBrush,这显然与带有颜色名称的string不一样。 -
@dubstylee 以下是错误运算符 '!=' 不能应用于类型为 'Windows.UI.Xaml.Media.Brush' 和 'Windows.UI.Color' 运算符 '!=' 的操作数不能应用于“Windows.UI.Xaml.Media.Brush”和“字符串”类型的操作数
-
简短回答:将
"Red"替换为Brushes.Red。更详细的答案如下。 -
它是一个画笔,有几种可能的具体画笔类型。取决于你如何设计它。也许您可以将 Background 转换为 (SolidColorBrush),这是一个常见的选择,现在您可以使用它的 Color 属性。也可以是 GradientBrush 或 TileBrush,它们当然不只有一种颜色。
-
@HansPassant 是的,投射背景效果很好。感谢您的帮助,我已经发布了答案。
标签: c# xaml winrt-xaml