以编程方式更改字体

Jim*_*Jim 7 c#

C#不喜欢以下代码:

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

有没有办法以编程方式执行此操作?

Tim*_*son 18

实例Font是不可变的.您需要构造一个new Font并将其分配给Font属性.该Font课程有各种各样的构造者用于此目的; 他们复制另一个实例并更改流程中的样式.

  • +1并且只是为了得到很好的答案:btnSizeRandom.Font = new Font(btnSizeRandom.Font,FontStyle.Bold); (11认同)

Han*_*ant 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);
    }
Run Code Online (Sandbox Code Playgroud)