【问题标题】:c# - Hide button text when another button is clickedc# - 单击另一个按钮时隐藏按钮文本
【发布时间】:2012-12-14 01:57:33
【问题描述】:

我正在尝试创建一个包含 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

【问题讨论】:

  • 您需要确保所有按钮都使用相同的事件处理程序。如果没有人能打败我,我会尽快给你打一个例子:)

标签: c# button tags


【解决方案1】:

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

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

【讨论】:

  • Eric,以上,如果我理解正确的话,你已经将字符串静态分配给相应的按钮了吗?我有 2 个数组,一个用于按钮名称,即“按钮 1”、“按钮 2”..等。第二个数组提取汽车名称。并将汽车名称随机分配给一个随机按钮。最终目标是匹配游戏。 12 个按钮,6 个不同的车名……等等
  • 是的,我只是展示了如何跟踪单击的按钮...并将文本切换回...您最初如何填充标签和文本属性并不相关。
  • 完美运行!谢谢埃里克。
【解决方案2】:

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

【讨论】:

  • 我的项目要求它需要是按钮:/
  • 如“您必须使用 System.Windows.Forms.Button 控件”?否则,我的建议会让屏幕上出现按钮的每一个外观。
猜你喜欢
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 2015-07-04
  • 1970-01-01
  • 2011-08-15
  • 2014-07-02
  • 1970-01-01
相关资源
最近更新 更多