1

我正在尝试创建一个包含 12 个按钮的匹配游戏。该程序从一个包含 12 个字符串的数组中分配一个随机字符串。当按钮被按下时,标签被传递给 button.text。例如,我现在想要完成的是。如果我按下“按钮 1”,它的文本将变为“Chevy Camaro”。如果我接下来按下“按钮 4”,我希望 button1.text 恢复为“按钮 1”,而不是“Chevy Camaro”的标签值。并且以同样的方式,由于按下“按钮 4”,我希望它显示标签.....

每个按钮都有与其相似的代码,除了按钮#,它当然会根据正在使用的按钮而变化。

我不确定如何声明,如果按钮是当前活动项,则显示它的标记属性,否则,恢复。

private void button4_Click(object sender, EventArgs e)     
{
    button4.Text = button4.Tag.ToString();

    buttoncount++;
    label2.Text = buttoncount.ToString();
}

提前感谢您的所有帮助。慢慢学这些东西.... =p

4

2 回答 2

2

您可以跟踪单击的最后一个按钮:

public partial class Form1 : Form
{
    Button lastButton = null;
    int buttoncount;

    public Form1()
    {
        InitializeComponent();
        button1.Tag = "Ford Mustang";
        button2.Tag = "Ford Focus";
        button3.Tag = "Chevy Malibu";
        button4.Tag = "Chevy Camaro";
        button1.Click += button_Click;
        button2.Click += button_Click;
        button3.Click += button_Click;
        button4.Click += button_Click;
        //etc...
    }

    void button_Click(object sender, EventArgs e)
    {
        if (lastButton != null)
        {
            SwitchTagWithText();
        }

        lastButton = sender as Button;
        SwitchTagWithText();

        buttoncount++;
        label2.Text = buttoncount.ToString();
    }

    void SwitchTagWithText()
    {
        string text = lastButton.Text;
        lastButton.Text = lastButton.Tag.ToString();
        lastButton.Tag = text;
    }
}
于 2012-12-14T02:30:02.253 回答
0

您可以使用外观设置为按钮的 RadioButton 控件吗?用这些替换所有按钮,将它们放在 GroupBox 中,并且可以自动处理单击时外观的“还原”。要更新文本,可以使用如下所示的简单事件处理程序;

    private void MakeButton()
    {
        RadioButton rb = new RadioButton
        {
            Appearance = Appearance.Button,
            Tag = "Chevy Camero"
        };
        rb.CheckedChanged += rb_CheckedChanged;
    }

    private void rb_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton clickedButton = sender as RadioButton;
        string currentText = clickedButton.Text;
        clickedButton.Text = clickedButton.Tag.ToString();
        clickedButton.Tag = currentText;
    }
于 2012-12-14T02:33:49.773 回答