簡體   English   中英

C#全局組件代碼

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

現在,在我解釋了我的問題之后,我可能會問您是否可以提供幫助,我們將不勝感激。

您可以創建一個將ControlColor作為參數的方法,並且從Control繼承的所有內容(即TextBoxDropDownListLabel等)都可以與此一起使用:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM