This is my class, where I have various properties and also the Panel control:
public class Square
{
private Panel _pSquare;
public Panel PSquare
{
get { return _pSquare; }
set { _pSquare = value; }
}
....
This is the Form Load EventHandler, where a bunch of Square Objects are created:
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;
开发者_如何学Go...
When the user clicks on a Panel, the pSquare_Click EventHandler is called, so that part works.
private void pSquare_Click(object sender, EventArgs e)
{
The problem I have is: how to access the properties of class Square in this EventHandler?
Whenever create a panel, Use the panel.Tag
to links each panel with its square:
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
}
Your Square class could look like this:
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);
}
}
}
In your form you could make the panels first, and then generate a collection of squares by looping through the panels:
foreach (Panel panel in this.Controls.OfType<Panel>())
{
var square = new Square(panel);
square.SquareClicked += this.squareClicked;
}
精彩评论