[英]Creating multiple buttons of the same class
我正在尝试创建一个大约25个按钮类的ButtonControls
,它们继承自具有嵌套for
循环的普通Button
类以创建正方形。 我添加了特殊的属性,称为coordsX
和coordsY
我用它们来了解应将它们放置在表单中的什么位置,而对于某些其他用途,在这里很难解释。 当我创建一个按钮时,将其放置在应有的位置,并在其文本中写上“ coords”,并显示正确的值,但是当我单击它时,消息框应该弹出并给我该按钮的坐标,但始终显示最后创建的按钮的坐标。
private void CreateBoard()
{
for (int x=0;x<BoardWidth;x++)
{
for (int y=0;y<BoardHeight;y++)
{
ButtonControls bc = new ButtonControls(x,y,PieceSize);
//bc.Name = x+"_"+y;
//bc.BackgroundImage = PieceBmp;
//bc.Size = new Size(PieceSize,PieceSize);
bc.Click += PieceButton_Click;
Point docks = new Point(20, 20);
docks.Offset(ButtonControls.coordsX, ButtonControls.coordsY);
bc.Location = docks;
Controls.Add(bc);
}
}
}
使用中的构造函数如下所示:
public ButtonControls (int X,int Y, int ButtonSize)
{
coordsX = X*ButtonSize;
coordsY = Y*ButtonSize;
Name = X+"."+Y;
BackColor = Color.White;
Size = new Size(ButtonSize,ButtonSize);
Font = new Font("Arial",6);
Text = coordsX + "." + coordsY;
}
public static int coordsX { get; set; }
public static int coordsY { get; set; }
和点击事件是这样的:
private void PieceButton_Click (object sender,EventArgs e)
{
MessageBox.Show(ButtonControls.coordsX+"/"+ButtonControls.coordsY);
}
如何使其显示我单击的按钮的坐标?
问题是您的坐标是static
。
删除static
即。
public int coordsX { get; set; }
public int coordsY { get; set; }
然后,使用sender
实例而不是类来在click事件中访问这些属性。
private void PieceButton_Click (object sender,EventArgs e)
{
var button = (ButtonControls)sender;
MessageBox.Show(button.coordsX+"/"+ button.coordsY);
}
附带说明一下,您的类名称ButtonControls
不好-为什么它是复数? ButtonControl
更好,但是它仍然没有描述它继承的类的区别... PieceButton
甚至更好(我不知道上下文,这只是一个猜测),但我个人将其称为Piece
...
将您的发件人投射到BottonControls
以使按钮被单击
然后,要访问属性coordsX , coordsY,
必须删除static
关键字
public int coordsX { get; set; }
public int coordsY { get; set; }
private void PieceButton_Click (object sender,EventArgs e)
{
var button = (ButtonControls)sender;
MessageBox.Show(button.coordsX+"/"+ button.coordsY);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.