[英]Toggling the appearance of a button winform
我在面板中有一個按鈕列表(動態生成)。 在我的應用程序中,當單擊其中一個按鈕時,其外觀應發生變化。 如果用戶更改選擇並單擊列表中的另一個按鈕,則新按鈕將更改外觀,而舊按鈕將恢復其默認外觀。
單擊完全不相關的按鈕可確認選擇。
我該怎么辦? 更改外觀並不是真正的問題,但知道存在先前的選擇並還原就可以了。
謝謝。
為面板中的所有按鈕創建一個按鈕單擊事件處理程序,並在那里處理所有更新:
private void MyToggleButton_Click(object sender, EventArgs e) {
// Set all Buttons in the Panel to their 'default' appearance.
var panelButtons = panel.Controls.OfType<Button>();
foreach (Button button in panelButtons) {
button.BackColor = Color.Green;
// Other changes...
}
// Now set the appearance of the Button that was clicked.
var clickedButton = (Button)sender;
clickedButton.BackColor = Color.Red;
// Other changes...
}
您可以不使用變量來存儲當前選擇的按鈕嗎
偽代碼
按鈕b = selectedButton
在點擊事件中
如果b!=發送者
恢復b
b =新選擇的按鈕
有一個存儲當前按鈕的變量,請確保在分配新單擊的按鈕之前先更改先前分配的按鈕的顏色
private Button currentBtn = null;
為按鈕創建一個公共事件處理程序
protected void b_Click(object sender, EventArgs e)
{
Button snder = sender as Button;
//for the first time just assign this button
if (currentBtn == null)
{
currentBtn = snder;
}
else //for the second time and beyond
{
//change the previous button to previous colour. I assumed red
currentBtn.BackColor = System.Drawing.Color.Red;
//assign the newly clicked button as current
currentBtn = snder;
}
//change the newly clicked button colour to "Active" e.g green
currentBtn.BackColor = System.Drawing.Color.Green;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.