【发布时间】:2013-03-22 14:48:48
【问题描述】:
我在窗口的主网格中创建了一个按钮矩阵,并且还为每个按钮创建了事件。 我还有一个整数矩阵,其中包含每个按钮的一些属性(例如 int a[1,2] 是按钮 btn[1,2] 的属性)。 我打算创建一个类似迷宫的东西,你只能通过骑士(从国际象棋)方式跳跃从一个按钮传递到另一个按钮。我不知道如何找到按下按钮的坐标,以便我可以改变位置当前按钮的。
Button[,] btn = new Button[25, 25];
for (x = 5; x <= n; x++)
{
for (y = 5; y <= n; y++)
{
btn[x, y] = new Button();
left += 72;
btn[x,y].Margin =new Thickness(left,top,0,0);
btn[x,y].Height = 32;
btn[x,y].Width = 32;
btn[x, y].Click += new RoutedEventHandler(btn_Click);
if (a[x, y] == 2)
btn[x,y].Background = Brushes.Red;
else
btn[x,y].Background = Brushes.Blue;
main.Children.Add(btn[x, y]);
}
left = 0;
top += 72;
}
}
private void btn_Click(object sender, RoutedEventArgs e)
{
}
【问题讨论】:
-
在 btn_Click() 中你可以这样做: Button btn = (Button)sender;
-
@Dilshod 是的,但为了安全起见
Button btn = sender as Button;,如果发送者没有按钮,将返回null,而不是抛出异常。 -
你是对的。或者你可以先检查:if(sender is Button){//then cast it}
-
如果我这样做,我的坐标会在哪里?
-
@bash.d 为什么要设置另一个控件来触发
btn_Click?如果这样做了,我会希望程序崩溃,以便我可以立即修复它!
标签: c# button wpf-controls