[英]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.