2010-06-30 24 views
7

C#不喜歡下面的代碼:更改字體編程

private void btnSizeRandom_Click(object sender, EventArgs e) 
{ 
    btnSizeRandom.Font.Bold = true; 
    btnother.Font.Bold = false; 
} 

有沒有辦法以編程方式做到這一點?

+3

這是什麼感覺? – FrustratedWithFormsDesigner 2010-06-30 20:40:05

回答

18

Font的實例是不可變的。您需要構建新的Font並將其分配給Font屬性。爲此,Font類具有各種構造函數;他們複製另一個實例並更改過程中的樣式。

+11

+1只是爲了得出最佳答案:btnSizeRandom.Font = new Font(btnSizeRandom.Font,FontStyle.Bold); – SwDevMan81 2010-06-30 20:55:57

+0

@ SwDevMan81此外,您需要: new system.Drawing.Font(btnSizeRandom.Font,FontStyle.Regular); – Recipe 2013-07-26 08:46:05

11
private static Font ChangeBoldStyle(Font org, bool bold) { 
     FontStyle style = org.Style; 
     if (bold) style |= FontStyle.Bold; 
     else style &= ~FontStyle.Bold; 
     return new Font(org, style); 
    }