繁体   English   中英

c#-单击另一个按钮时隐藏按钮文本

[英]c# - Hide button text when another button is clicked

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

除了按钮#之外,每个按钮都有与其类似的代码,当然,这些代码会根据所使用的按钮而变化。

我不确定如何声明,如果button是当前活动项,则显示其tag属性,否则,返回原状态。

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

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

预先感谢您的所有帮助。 慢慢学习这些东西。

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

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

您可以使用外观设置为button的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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM