【问题标题】:How to update existing Font in Windows Forms如何更新 Windows 窗体中的现有字体
【发布时间】:2018-02-20 11:02:49
【问题描述】:

在 Windows 窗体中,我有一个文本框,我希望用户设置它的字体样式。

类似:

   Font font = new Font(textBox1.Font,FontStyle.Regular);
   if (checkBox1.Checked == true)
        font= new Font(font,FontStyle.Bold);
   if (checkBox2.Checked == true)
        font = new Font(font, FontStyle.Italic);
   if (checkBox3.Checked == true)
        font = new Font(font, FontStyle.Underline);
   textBox1.Font = font;

问题是,如果选择了两个复选框,我将不得不这样做:

font = new Font(font, FontStyle.Italic|FontStyle.Italic);

然后检查所有可能的组合。 有没有办法定义字体然后为其样式添加属性?而不是检查所有可能的 if 组合。

类似:

Font font= new Font();
if (checkBox1.Checked == true)
        font.Bold=true;
   if (checkBox2.Checked == true)
        font.Italic=true;
   if (checkBox3.Checked == true)
        font.Underline=true;

【问题讨论】:

  • 你不能只为复选框而不是 if 语句创建事件,那么你一次只需要调整一个属性?
  • 你是对的,但问题仍然存在,如何调整属性?
  • 设置字体后,我找不到再次更新其样式的方法

标签: c# winforms fonts textbox


【解决方案1】:

字体是不可变的,因此字体一旦创建就无法更改。
你可以做的是有一个变量来保存字体样式,然后做这样的事情:

var fontStyle = FontStyle.Regular;

if (checkBox1.Checked)
    {fontStyle |= FontStyle.Bold;}
if (checkBox2.Checked)
    {fontStyle |= FontStyle.Italic;}
if (checkBox3.Checked)
    {fontStyle |= FontStyle.Underline;}

textBox1.Font = new Font(textBox1.Font, fontStyle);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2014-11-20
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    相关资源
    最近更新 更多