【问题标题】:Single method for multiple button backgroind image changes?多个按钮背景图像更改的单一方法?
【发布时间】:2021-04-07 10:20:21
【问题描述】:

我是新来的。如果您能帮助我编写一个可以更改单击按钮的背景图像的方法,我会很高兴。

这就是我现在正在做的事情。正如你所看到的,我正在为每个按钮做这件事。我很想知道是否有一种方法可以执行按钮只会调用的一种方法。

这是一个简单的井字游戏多人游戏。

private void cell23_Click(object sender, EventArgs e)
    {
        if (gameGrid[1, 2] == "n")
        {
            if (currentPlayer == "x")
            {
                this.cell23.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.cross));
                currentPlayer = "o";
                gameGrid[1, 2] = "x";
                cell23.Enabled = false;
            }
            else if (currentPlayer == "o")
            {
                this.cell23.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.nought));
                currentPlayer = "x";
                gameGrid[1, 2] = "o";
                cell23.Enabled = false;
            }

        }

编辑:

private void AnyCell_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        switch (btn.Tag)
        {
            case "cell11":
                ButtonPressed(0,0); break;
            case "two":
            case "three":

            default: break;
        }
    }

现在我有了这个方法。当我按下带有标签 cell11 的按钮以在此处访问此代码时,我该怎么做?

【问题讨论】:

  • cell23是什么类型?
  • 我认为点击的单元格实例在 sender 参数中。
  • 如果这是您所要求的,所有单元格$$ 都是按钮

标签: c# button background


【解决方案1】:

使用sender 参数,该参数(通常)设置为引发事件的对象。

private void AnyCell_Click(object sender, EventArgs e)
{
    var clickedCell = sender as Control; //Or whatever type it is

    if (gameGrid[1, 2] == "n")
    {
        if (currentPlayer == "x")
        {
            clickedCell.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.cross));
            currentPlayer = "o";
            gameGrid[1, 2] = "x";
            clickedCell.Enabled = false;
        }
        else if (currentPlayer == "o")
        {
            clickedCell.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.nought));
            currentPlayer = "x";
            gameGrid[1, 2] = "o";
            clickedCell.Enabled = false;
        }
    }

【讨论】:

  • 一旦我尝试在按钮中调用该方法,它会给出:没有给出的参数对应于所需的形式参数“sender”
  • 这是点击处理程序。你不叫它。您将其注册为您的事件处理程序。如果您尝试从事件处理程序中调用它,只需传递参数即可。
  • 我已经编辑了我的问题,请您查看一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 2013-09-07
  • 2016-07-12
相关资源
最近更新 更多