2016-03-11 84 views
1

我想提出一個通用軟件,並在其中我加了一些標籤(我不能告訴更多... XD) 所以,我通過各種控制要循環在我的表或者至少所有的標籤...我已經試過循環通過所有控件[MaterialSkin](C#)

foreach (Control c in this.Controls) 
{ 
    //item.Font.Size = 11f; 
    c.ForeColor = Color.White; 
} 

但我認爲這只是循環到MaterialSkin.Controls.MaterialTabControl

,因爲當我嘗試用MaterialLabel..etc

foreach (MaterialLabel c in this.Controls) 
    { 
     //item.Font.Size = 11f; 
     c.ForeColor = Color.White; 
    } 
運行任意代碼

它告訴我

Additional information: Unable to cast object of type 'MaterialSkin.Controls.MaterialTabControl' to type 'MaterialSkin.Controls.MaterialLabel'. 

我需要幫助,請幫助我:) 我不是一個很優秀的程序員......所以,請幫助

現在要發揮造成4人死亡的xD

+1

'foreach(MaterialLabel c in this.Controls.OfType ())' – LarsTech

回答

1

之前改變任何財產檢查,如果它是類型MaterialLabel

foreach (Control c in this.Controls) 
{ 
    if(c.GetType()==typeof(MaterialLabel)) 
    { 
     c.Font = new Font(c.Font, FontStyle.Bold); 
     c.ForeColor = Color.White; 
    } 
} 

或LarsTech說:

foreach (MaterialLabel c in this.Controls.OfType<MaterialLabel>()) 
{ 
    c.Font = new Font(c.Font, FontStyle.Bold); 
    c.ForeColor = Color.White; 
} 
+0

我認爲它甚至沒有達到其他控件...它在Tabcontrol上結束,就是這樣...它不工作一個循環,但如果我通常用它它的作品 你也可以告訴我如何讓它大膽的,因爲當我使用'c.Font.Bold = TRUE;'它說,它不能被分配,因爲它是隻讀 –

+0

@RajaBilal我編輯我的答案。請看看它 –

+0

我告訴你們,這是不工作...代碼是不工作...看我的評論再次請 –

0

幾個選項...

foreach (var c in this.Controls) 
{ 
    if(c is MaterialLabel) 
    { 
     var i = (MaterialLabel)c; 
     i.Font = new Font(c.Font, FontStyle.Bold); 
     i.ForeColor = Color.White; 
    } 
} 

...

foreach (var c in this.Controls) 
{ 
    //slightly faster than the first version but won't work with struct 
    var i = c as MaterialLabel; 
    if(i != null) 
    { 
     i.Font = new Font(c.Font, FontStyle.Bold); 
     i.ForeColor = Color.White; 
    } 
} 

...

//cleanest 
foreach (var c in this.Controls.OfType<MaterialLabel>()) 
{ 
    c.Font = new Font(c.Font, FontStyle.Bold); 
    c.ForeColor = Color.White; 
} 
+0

非正常工作。 ..是因爲我使用自定義字體,當我默認設置顏色時,它會自動更改爲黑色...甚至文件+ complied exe,但是當我在像'conditionlbl.ForeColor = Color這樣的文件中執行它時。白色;'它的工作原理......但它不是通過一個循環,而不是由默認設置 –

+0

我使用這裏提供的方法http://hongouru.blogspot.com/2010/10/c-how-to-add-工作字體-TTF真型fonts.html使用自定義字體... –

+0

這也可能是因爲我使用的材料標籤,並沒有在系統的控制庫中存在...他們是選項卡控件內並在2至3面板...和唯一得到的直到選項卡控制...不是更多裏面我的意思是在這些面板內... –