[英]C# Global Component Code
我是C#的新手,到目前為止,我一直在弄亂發現這種語言,我在追求中編寫了許多程序,但是現在我只能堅持一件事,我無法用單詞解釋,但是代碼可以說我想要所以我們開始吧,我知道這是一個愚蠢的計划,但僅用於教育目的:D
Private void change()
{
anycontrol.BackColor = Color.Gold; // when this function called the control's BackColor will Change to gold
}
// example
private void TextBox1_Focused(object sender, EventArgs e)
{
Change(); // this suppose to change the color of the controls which is now textbox1 i want it to work on other controls such as buttons progressbars etc
}
現在,在我解釋了我的問題之后,我可能會問您是否可以提供幫助,我們將不勝感激。
您可以創建一個將Control和Color作為參數的方法,並且從Control
繼承的所有內容(即TextBox
, DropDownList
, Label
等)都可以與此一起使用:
void SetControlBackgroundColour(Control control, Color colour)
{
if (control != null)
{
control.BackColor = colour;
}
}
在您的示例中,可以這樣使用它:
private void TextBox1_Focused(object sender, EventArgs e)
{
SetControlBackgroundColour(sender as Control, Color.Gold);
}
為了回應評論,您可以在遞歸方法中使用此方法,該方法將為表單上的每個控件設置背景色:
void SetControlBackgroundColourRecursive(Control parentControl, Color colour)
{
if (parentControl != null)
{
foreach (Control childControl in parentControl.Controls)
{
SetControlBackgroundColour(childControl, colour);
SetControlBackgroundColourRecursive(childControl);
}
}
}
然后在Form1_Load
方法中的Form
對象( this
)上調用此函數(假設表單稱為Form1
):
protected void Form1_Load(object sender, EventArgs e)
{
SetControlBackgroundColourRecursive(this, Color.Gold);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.