我正在编写点击红色背景按钮的功能。 此功能无效。 我有40个具有相同功能的按钮,用于点击" ButClick"。 但当我点击任何按钮(例如绿色背景)时 - 计数器计数。我只想在点击红色背景的按钮时才这样做。
private void But_Click(object sender, RoutedEventArgs e)
{
var column = Grid.GetColumn(sender as Button);
var row = Grid.GetRow(sender as Button);
LabelX.Content = column.ToString();
LabelY.Content = row.ToString();
if ((sender as Button).Background == new SolidColorBrush(Colors.Red));
{
counts += 1;
LabelCounterOfClick.Content = counts.ToString();
}
}
更新
现在它没有计算任何东西。当我点击任何按钮 - 计数器显示0.如果错误(它没有检测到红色),我的功能是什么东西
private void But_Click(object sender, RoutedEventArgs e)
{
var column = Grid.GetColumn(sender as Button);
var row = Grid.GetRow(sender as Button);
LabelX.Content = column.ToString();
LabelY.Content = row.ToString();
if ((sender as Button).Background == new SolidColorBrush(Colors.Red))
{
counts += 1;
}
else
{
counts = 0;
}
LabelCounterOfClick.Content = counts.ToString();
}
代码的最新消息。
namespace Silnik_Zmiany_koloru
{
public partial class MainWindow : Window
{
public Random _random;
public MainWindow()
{
InitializeComponent();
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromSeconds(1);
dt.Tick += Dt_Tick;
dt.Start();
}
private void Dt_Tick(object sender, EventArgs e)
{
Losowanie(); // zmiana kolorow (losowe)
}
int counts = 0;
private void But0_0_Click(object sender, RoutedEventArgs e)
{
Losowanie();
}
private Random random = new Random();
private Random random1 = new Random();
int ilosc_kolorow = 3;
private Color[] colors = new Color[]
{
Colors.Red,
Colors.Blue,
Colors.Green,
};
private void Losowanie()
{
for (int i = 0; i <= 6; i++)
{
for (int k = 3; k <= 10; k++)
{
var ele = MainGrid.FindName("But" + i + "_" + random.Next(0, 8));
Button button = ele as Button;
if (button != null)
{
Change_color(button);
}
}
}
}
}
}
答案 0 :(得分:2)
尝试在条件
之后删除行末尾的;您可以使用“ Brushes.Red ”检查背景,而不是创建新对象
答案 1 :(得分:1)
为什么要将ButClick事件附加到所有40个按钮?为什么不把它添加到那些红色? 选择按钮上的属性,并将click事件分配给应该拥有它的人。
答案 2 :(得分:0)
记住纠正AbduGo。
不是最好的解决方案,但尝试这样做,
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
Brush btnBrush = btn.Background;
string color = "";
if (btnBrush is SolidColorBrush)
{
color = ((SolidColorBrush)btnBrush).Color.ToString();
}
if (color == Brushes.Red.ToString())
{
//your logic of incrementing counter
}
else
{
//your logic of resting counter
}
}