如果我在10 x 10网格中有一个Panel数组,并且我用x和y坐标描述了每个面板位置,我怎么能将它传递给Panel.click事件?
int sqSize = 80;
int bAcross = 10;
CPanels = new Panel[bAcross, bAcross]; //10 * 10 grid
for (int y = 0; y < bAcross; y++)
{
for (int x = 0; x < bAcross; x++)
{
var newPan = new Panel
{
Size = new Size(sqSize, sqSize),
Location = new Point(x * sqSize, y * sqSize)
};
Controls.Add(newPan);
CPanels[x, y] = newPan; //add to correct location on grid
newPan.Click += Pan_Click;
在点击事件中我需要做什么?
private void Pan_Click(object sender, EventArgs e)
{
int x = (extract x coord)
int y = (extract y coord)
}
编辑:澄清我正在寻找网格中的位置。基本上,网格中的左上角应为0,0,右下角应为10,10。
答案 0 :(得分:2)
Panel
参数中提供了触发Pan_Click
事件的sender
:
private void Pan_Click(object sender, EventArgs e)
{
var panel = sender as Panel;
if (panel == null)
return;
int x = panel.Location.X;
int y = panel.Location.Y;
}
由于您实际上希望Panel
的位置与10x10网格相关,并且您需要通过将Panel
乘以当前sqSize
来设置每个Location = new Point(x * sqSize, y * sqSize)
的位置网格中的位置:
sqSize
您可以再次将每个坐标再次划分为x
,以获得原始的y
和private void Pan_Click(object sender, EventArgs e)
{
var panel = sender as Panel;
if (panel == null)
return;
int x = panel.Location.X / sqSize;
int y = panel.Location.Y / sqSize;
}
值:
{{1}}
(另请注意,如果它是10x10网格,右下角将是9,9而不是10,10)