这是我的类,我有各种属性和面板控件:
public class Square
{
private Panel _pSquare;
public Panel PSquare
{
get { return _pSquare; }
set { _pSquare = value; }
}
....
这是Form Load EventHandler,其中创建了一堆正方形对象:
private void Form1_Load(object sender, EventArgs e)
{
for (var n = 0; n < gridSize; n++)
{
for (var m = 0; m < gridSize; m++)
{
Square squareboard = new Square(n, m);
squareboard.PSquare.Click += squareEvent;
...
当用户点击面板时,pSquare_Click EventHandler被调用,因此该部分工作。
private void pSquare_Click(object sender, EventArgs e)
{
我的问题是:如何在这个EventHandler中访问类Square的属性?
无论何时创建面板,使用panel.Tag
将每个面板与其正方形链接:
private void Form1_Load(object sender, EventArgs e)
{
for (var n = 0; n < gridSize; n++)
{
for (var m = 0; m < gridSize; m++)
{
Square squareboard = new Square(n, m);
squaredboard.PSquare.Tag = squareboard;
squareboard.PSquare.Click += squareEvent;
...
private void pSquare_Click(object sender, EventArgs e)
{
Panel panel = (Panel)sender;
Square square = (Square)panel.Tag;//access to the underlying square object
}
你的Square类可以像这样:
public class Square
{
private readonly Panel _pSquare;
public Square(Panel pSquare)
{
this._pSquare = pSquare;
this._pSquare.Click += this._pSquare_Click;
}
void _pSquare_Click(object sender, EventArgs e)
{
this.onSquareClicked();
}
public event EventHandler SquareClicked;
private void onSquareClicked()
{
EventHandler eventHandler = this.SquareClicked;
if (eventHandler != null)
{
eventHandler(this, EventArgs.Empty);
}
}
}
在您的表单中,您可以先制作面板,然后通过循环面板生成一个正方形集合:
foreach (Panel panel in this.Controls.OfType<Panel>())
{
var square = new Square(panel);
square.SquareClicked += this.squareClicked;
}