如何在EventHandler中确定Control属于哪个类?

时间:2011-07-26 12:32:30

标签: .net properties event-handling

这是我的班级,我有各种属性和Panel控件:

public class Square
{
    private Panel _pSquare;
    public Panel PSquare
    {
        get { return _pSquare; }
        set { _pSquare = value; }
    }
    ....

这是Form Load EventHandler,其中创建了一堆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);

            squareboard.PSquare.Click += squareEvent;
             ...

当用户点击Panel时,会调用pSquare_Click EventHandler,因此该部分可以正常工作。

private void pSquare_Click(object sender, EventArgs e)
{

我遇到的问题是:如何在此EventHandler中访问Square类的属性?

2 个答案:

答案 0 :(得分:2)

每当创建一个面板时,使用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
}

答案 1 :(得分:1)

你的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;
    }